costmodel.go 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098
  1. package costmodel
  2. import (
  3. "errors"
  4. "fmt"
  5. "maps"
  6. "math"
  7. "regexp"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/opencost/opencost/core/pkg/clustercache"
  12. "github.com/opencost/opencost/core/pkg/clusters"
  13. coreenv "github.com/opencost/opencost/core/pkg/env"
  14. "github.com/opencost/opencost/core/pkg/filter/allocation"
  15. "github.com/opencost/opencost/core/pkg/log"
  16. "github.com/opencost/opencost/core/pkg/opencost"
  17. "github.com/opencost/opencost/core/pkg/source"
  18. "github.com/opencost/opencost/core/pkg/util"
  19. "github.com/opencost/opencost/core/pkg/util/promutil"
  20. costAnalyzerCloud "github.com/opencost/opencost/pkg/cloud/models"
  21. v1 "k8s.io/api/core/v1"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/apimachinery/pkg/labels"
  24. "golang.org/x/sync/singleflight"
  25. )
  26. const (
  27. profileThreshold = 1000 * 1000 * 1000 // 1s (in ns)
  28. unmountedPVsContainer = "unmounted-pvs"
  29. )
  30. // isCron matches a CronJob name and captures the non-timestamp name
  31. //
  32. // We support either a 10 character timestamp OR an 8 character timestamp
  33. // because batch/v1beta1 CronJobs creates Jobs with 10 character timestamps
  34. // and batch/v1 CronJobs create Jobs with 8 character timestamps.
  35. var isCron = regexp.MustCompile(`^(.+)-(\d{10}|\d{8})$`)
  36. type CostModel struct {
  37. Cache clustercache.ClusterCache
  38. ClusterMap clusters.ClusterMap
  39. BatchDuration time.Duration
  40. RequestGroup *singleflight.Group
  41. DataSource source.OpenCostDataSource
  42. Provider costAnalyzerCloud.Provider
  43. pricingMetadata *costAnalyzerCloud.PricingMatchMetadata
  44. }
  45. func NewCostModel(
  46. dataSource source.OpenCostDataSource,
  47. provider costAnalyzerCloud.Provider,
  48. cache clustercache.ClusterCache,
  49. clusterMap clusters.ClusterMap,
  50. batchDuration time.Duration,
  51. ) *CostModel {
  52. // request grouping to prevent over-requesting the same data prior to caching
  53. requestGroup := new(singleflight.Group)
  54. return &CostModel{
  55. Cache: cache,
  56. ClusterMap: clusterMap,
  57. BatchDuration: batchDuration,
  58. DataSource: dataSource,
  59. Provider: provider,
  60. RequestGroup: requestGroup,
  61. }
  62. }
  63. type CostData struct {
  64. Name string `json:"name,omitempty"`
  65. PodName string `json:"podName,omitempty"`
  66. NodeName string `json:"nodeName,omitempty"`
  67. NodeData *costAnalyzerCloud.Node `json:"node,omitempty"`
  68. Namespace string `json:"namespace,omitempty"`
  69. Deployments []string `json:"deployments,omitempty"`
  70. Services []string `json:"services,omitempty"`
  71. Daemonsets []string `json:"daemonsets,omitempty"`
  72. Statefulsets []string `json:"statefulsets,omitempty"`
  73. Jobs []string `json:"jobs,omitempty"`
  74. RAMReq []*util.Vector `json:"ramreq,omitempty"`
  75. RAMUsed []*util.Vector `json:"ramused,omitempty"`
  76. RAMAllocation []*util.Vector `json:"ramallocated,omitempty"`
  77. CPUReq []*util.Vector `json:"cpureq,omitempty"`
  78. CPUUsed []*util.Vector `json:"cpuused,omitempty"`
  79. CPUAllocation []*util.Vector `json:"cpuallocated,omitempty"`
  80. GPUReq []*util.Vector `json:"gpureq,omitempty"`
  81. PVCData []*PersistentVolumeClaimData `json:"pvcData,omitempty"`
  82. NetworkData []*util.Vector `json:"network,omitempty"`
  83. Annotations map[string]string `json:"annotations,omitempty"`
  84. Labels map[string]string `json:"labels,omitempty"`
  85. NamespaceLabels map[string]string `json:"namespaceLabels,omitempty"`
  86. ClusterID string `json:"clusterId"`
  87. ClusterName string `json:"clusterName"`
  88. }
  89. func (cd *CostData) String() string {
  90. return fmt.Sprintf("\n\tName: %s; PodName: %s, NodeName: %s\n\tNamespace: %s\n\tDeployments: %s\n\tServices: %s\n\tCPU (req, used, alloc): %d, %d, %d\n\tRAM (req, used, alloc): %d, %d, %d",
  91. cd.Name, cd.PodName, cd.NodeName, cd.Namespace, strings.Join(cd.Deployments, ", "), strings.Join(cd.Services, ", "),
  92. len(cd.CPUReq), len(cd.CPUUsed), len(cd.CPUAllocation),
  93. len(cd.RAMReq), len(cd.RAMUsed), len(cd.RAMAllocation))
  94. }
  95. func (cd *CostData) GetController() (name string, kind string, hasController bool) {
  96. hasController = false
  97. if len(cd.Deployments) > 0 {
  98. name = cd.Deployments[0]
  99. kind = "deployment"
  100. hasController = true
  101. } else if len(cd.Statefulsets) > 0 {
  102. name = cd.Statefulsets[0]
  103. kind = "statefulset"
  104. hasController = true
  105. } else if len(cd.Daemonsets) > 0 {
  106. name = cd.Daemonsets[0]
  107. kind = "daemonset"
  108. hasController = true
  109. } else if len(cd.Jobs) > 0 {
  110. name = cd.Jobs[0]
  111. kind = "job"
  112. hasController = true
  113. match := isCron.FindStringSubmatch(name)
  114. if match != nil {
  115. name = match[1]
  116. }
  117. }
  118. return name, kind, hasController
  119. }
  120. func (cm *CostModel) ComputeCostData(start, end time.Time) (map[string]*CostData, error) {
  121. // Cluster ID is specific to the source cluster
  122. clusterID := coreenv.GetClusterID()
  123. cp := cm.Provider
  124. ds := cm.DataSource
  125. mq := ds.Metrics()
  126. // Get Kubernetes data
  127. // Pull pod information from k8s API
  128. podlist := cm.Cache.GetAllPods()
  129. podDeploymentsMapping, err := getPodDeployments(cm.Cache, podlist, clusterID)
  130. if err != nil {
  131. return nil, err
  132. }
  133. podServicesMapping, err := getPodServices(cm.Cache, podlist, clusterID)
  134. if err != nil {
  135. return nil, err
  136. }
  137. namespaceLabelsMapping, err := getNamespaceLabels(cm.Cache, clusterID)
  138. if err != nil {
  139. return nil, err
  140. }
  141. namespaceAnnotationsMapping, err := getNamespaceAnnotations(cm.Cache, clusterID)
  142. if err != nil {
  143. return nil, err
  144. }
  145. // Get metrics data
  146. resRAMUsage, resCPUUsage, resNetZoneRequests, resNetRegionRequests, resNetInternetRequests, err := queryMetrics(mq, start, end)
  147. if err != nil {
  148. log.Warnf("ComputeCostData: continuing despite metrics errors: %s", err)
  149. }
  150. defer measureTime(time.Now(), profileThreshold, "ComputeCostData: Processing Query Data")
  151. nodes, err := cm.GetNodeCost()
  152. if err != nil {
  153. log.Warnf("GetNodeCost: no node cost model available: %s", err)
  154. return nil, err
  155. }
  156. // Unmounted PVs represent the PVs that are not mounted or tied to a volume on a container
  157. unmountedPVs := make(map[string][]*PersistentVolumeClaimData)
  158. pvClaimMapping, err := GetPVInfoLocal(cm.Cache, clusterID)
  159. if err != nil {
  160. log.Warnf("GetPVInfo: unable to get PV data: %s", err.Error())
  161. }
  162. if pvClaimMapping != nil {
  163. err = cm.addPVData(pvClaimMapping)
  164. if err != nil {
  165. return nil, err
  166. }
  167. // copy claim mappings into zombies, then remove as they're discovered
  168. for k, v := range pvClaimMapping {
  169. unmountedPVs[k] = []*PersistentVolumeClaimData{v}
  170. }
  171. }
  172. networkUsageMap, err := GetNetworkUsageData(resNetZoneRequests, resNetRegionRequests, resNetInternetRequests, clusterID)
  173. if err != nil {
  174. log.Warnf("Unable to get Network Cost Data: %s", err.Error())
  175. networkUsageMap = make(map[string]*NetworkUsageData)
  176. }
  177. containerNameCost := make(map[string]*CostData)
  178. containers := make(map[string]bool)
  179. RAMUsedMap, err := GetContainerMetricVector(resRAMUsage, clusterID)
  180. if err != nil {
  181. return nil, err
  182. }
  183. for key := range RAMUsedMap {
  184. containers[key] = true
  185. }
  186. CPUUsedMap, err := GetContainerMetricVector(resCPUUsage, clusterID) // No need to normalize here, as this comes from a counter
  187. if err != nil {
  188. return nil, err
  189. }
  190. for key := range CPUUsedMap {
  191. containers[key] = true
  192. }
  193. currentContainers := make(map[string]clustercache.Pod)
  194. for _, pod := range podlist {
  195. if pod.Status.Phase != v1.PodRunning {
  196. continue
  197. }
  198. cs, err := NewContainerMetricsFromPod(pod, clusterID)
  199. if err != nil {
  200. return nil, err
  201. }
  202. for _, c := range cs {
  203. containers[c.Key()] = true // captures any containers that existed for a time < a metrics scrape interval. We currently charge 0 for this but should charge something.
  204. currentContainers[c.Key()] = *pod
  205. }
  206. }
  207. missingNodes := make(map[string]*costAnalyzerCloud.Node)
  208. missingContainers := make(map[string]*CostData)
  209. for key := range containers {
  210. if _, ok := containerNameCost[key]; ok {
  211. continue // because ordering is important for the allocation model (all PV's applied to the first), just dedupe if it's already been added.
  212. }
  213. // The _else_ case for this statement is the case in which the container has been
  214. // deleted so we have usage information but not request information. In that case,
  215. // we return partial data for CPU and RAM: only usage and not requests.
  216. if pod, ok := currentContainers[key]; ok {
  217. podName := pod.Name
  218. ns := pod.Namespace
  219. nsLabels := namespaceLabelsMapping[ns+","+clusterID]
  220. podLabels := maps.Clone(pod.Labels)
  221. if podLabels == nil {
  222. podLabels = make(map[string]string)
  223. }
  224. for k, v := range nsLabels {
  225. if _, ok := podLabels[k]; !ok {
  226. podLabels[k] = v
  227. }
  228. }
  229. nsAnnotations := namespaceAnnotationsMapping[ns+","+clusterID]
  230. podAnnotations := pod.Annotations
  231. if podAnnotations == nil {
  232. podAnnotations = make(map[string]string)
  233. }
  234. for k, v := range nsAnnotations {
  235. if _, ok := podAnnotations[k]; !ok {
  236. podAnnotations[k] = v
  237. }
  238. }
  239. nodeName := pod.Spec.NodeName
  240. var nodeData *costAnalyzerCloud.Node
  241. if _, ok := nodes[nodeName]; ok {
  242. nodeData = nodes[nodeName]
  243. }
  244. nsKey := ns + "," + clusterID
  245. var podDeployments []string
  246. if _, ok := podDeploymentsMapping[nsKey]; ok {
  247. if ds, ok := podDeploymentsMapping[nsKey][pod.Name]; ok {
  248. podDeployments = ds
  249. } else {
  250. podDeployments = []string{}
  251. }
  252. }
  253. var podPVs []*PersistentVolumeClaimData
  254. podClaims := pod.Spec.Volumes
  255. for _, vol := range podClaims {
  256. if vol.PersistentVolumeClaim != nil {
  257. name := vol.PersistentVolumeClaim.ClaimName
  258. key := ns + "," + name + "," + clusterID
  259. if pvClaim, ok := pvClaimMapping[key]; ok {
  260. pvClaim.TimesClaimed++
  261. podPVs = append(podPVs, pvClaim)
  262. // Remove entry from potential unmounted pvs
  263. delete(unmountedPVs, key)
  264. }
  265. }
  266. }
  267. var podNetCosts []*util.Vector
  268. if usage, ok := networkUsageMap[ns+","+podName+","+clusterID]; ok {
  269. netCosts, err := GetNetworkCost(usage, cp)
  270. if err != nil {
  271. log.Debugf("Error pulling network costs: %s", err.Error())
  272. } else {
  273. podNetCosts = netCosts
  274. }
  275. }
  276. var podServices []string
  277. if _, ok := podServicesMapping[nsKey]; ok {
  278. if svcs, ok := podServicesMapping[nsKey][pod.Name]; ok {
  279. podServices = svcs
  280. } else {
  281. podServices = []string{}
  282. }
  283. }
  284. for i, container := range pod.Spec.Containers {
  285. containerName := container.Name
  286. // recreate the key and look up data for this container
  287. newKey := NewContainerMetricFromValues(ns, podName, containerName, pod.Spec.NodeName, clusterID).Key()
  288. // k8s.io/apimachinery/pkg/api/resource/amount.go and
  289. // k8s.io/apimachinery/pkg/api/resource/quantity.go for
  290. // details on the "amount" API. See
  291. // https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#resource-types
  292. // for the units of memory and CPU.
  293. ramRequestBytes := container.Resources.Requests.Memory().Value()
  294. // Because information on container RAM & CPU requests isn't
  295. // coming from metrics, it won't have a timestamp associated
  296. // with it. We need to provide a timestamp.
  297. RAMReqV := []*util.Vector{
  298. {
  299. Value: float64(ramRequestBytes),
  300. Timestamp: float64(time.Now().UTC().Unix()),
  301. },
  302. }
  303. // use millicores so we can convert to cores in a float64 format
  304. cpuRequestMilliCores := container.Resources.Requests.Cpu().MilliValue()
  305. CPUReqV := []*util.Vector{
  306. {
  307. Value: float64(cpuRequestMilliCores) / 1000,
  308. Timestamp: float64(time.Now().UTC().Unix()),
  309. },
  310. }
  311. gpuReqCount := 0.0
  312. if g, ok := container.Resources.Requests["nvidia.com/gpu"]; ok {
  313. gpuReqCount = g.AsApproximateFloat64()
  314. } else if g, ok := container.Resources.Limits["nvidia.com/gpu"]; ok {
  315. gpuReqCount = g.AsApproximateFloat64()
  316. } else if g, ok := container.Resources.Requests["k8s.amazonaws.com/vgpu"]; ok {
  317. gpuReqCount = g.AsApproximateFloat64()
  318. } else if g, ok := container.Resources.Limits["k8s.amazonaws.com/vgpu"]; ok {
  319. gpuReqCount = g.AsApproximateFloat64()
  320. }
  321. GPUReqV := []*util.Vector{
  322. {
  323. Value: float64(gpuReqCount),
  324. Timestamp: float64(time.Now().UTC().Unix()),
  325. },
  326. }
  327. RAMUsedV, ok := RAMUsedMap[newKey]
  328. if !ok {
  329. log.Debug("no RAM usage for " + newKey)
  330. RAMUsedV = []*util.Vector{{}}
  331. }
  332. CPUUsedV, ok := CPUUsedMap[newKey]
  333. if !ok {
  334. log.Debug("no CPU usage for " + newKey)
  335. CPUUsedV = []*util.Vector{{}}
  336. }
  337. var pvReq []*PersistentVolumeClaimData
  338. var netReq []*util.Vector
  339. if i == 0 { // avoid duplicating by just assigning all claims to the first container.
  340. pvReq = podPVs
  341. netReq = podNetCosts
  342. }
  343. costs := &CostData{
  344. Name: containerName,
  345. PodName: podName,
  346. NodeName: nodeName,
  347. Namespace: ns,
  348. Deployments: podDeployments,
  349. Services: podServices,
  350. Daemonsets: getDaemonsetsOfPod(pod),
  351. Jobs: getJobsOfPod(pod),
  352. Statefulsets: getStatefulSetsOfPod(pod),
  353. NodeData: nodeData,
  354. RAMReq: RAMReqV,
  355. RAMUsed: RAMUsedV,
  356. CPUReq: CPUReqV,
  357. CPUUsed: CPUUsedV,
  358. GPUReq: GPUReqV,
  359. PVCData: pvReq,
  360. NetworkData: netReq,
  361. Annotations: podAnnotations,
  362. Labels: podLabels,
  363. NamespaceLabels: nsLabels,
  364. ClusterID: clusterID,
  365. ClusterName: cm.ClusterMap.NameFor(clusterID),
  366. }
  367. var cpuReq, cpuUse *util.Vector
  368. if len(costs.CPUReq) > 0 {
  369. cpuReq = costs.CPUReq[0]
  370. }
  371. if len(costs.CPUUsed) > 0 {
  372. cpuUse = costs.CPUUsed[0]
  373. }
  374. costs.CPUAllocation = getContainerAllocation(cpuReq, cpuUse, "CPU")
  375. var ramReq, ramUse *util.Vector
  376. if len(costs.RAMReq) > 0 {
  377. ramReq = costs.RAMReq[0]
  378. }
  379. if len(costs.RAMUsed) > 0 {
  380. ramUse = costs.RAMUsed[0]
  381. }
  382. costs.RAMAllocation = getContainerAllocation(ramReq, ramUse, "RAM")
  383. containerNameCost[newKey] = costs
  384. }
  385. } else {
  386. // The container has been deleted. Not all information is sent to metrics via ksm, so fill out what we can without k8s api
  387. log.Debug("The container " + key + " has been deleted. Calculating allocation but resulting object will be missing data.")
  388. c, err := NewContainerMetricFromKey(key)
  389. if err != nil {
  390. return nil, err
  391. }
  392. // CPU and RAM requests are obtained from the Kubernetes API.
  393. // If this case has been reached, the Kubernetes API will not
  394. // have information about the pod because it no longer exists.
  395. //
  396. // The case where this matters is minimal, mainly in environments
  397. // with very short-lived pods that over-request resources.
  398. RAMReqV := []*util.Vector{{}}
  399. CPUReqV := []*util.Vector{{}}
  400. GPUReqV := []*util.Vector{{}}
  401. RAMUsedV, ok := RAMUsedMap[key]
  402. if !ok {
  403. log.Debug("no RAM usage for " + key)
  404. RAMUsedV = []*util.Vector{{}}
  405. }
  406. CPUUsedV, ok := CPUUsedMap[key]
  407. if !ok {
  408. log.Debug("no CPU usage for " + key)
  409. CPUUsedV = []*util.Vector{{}}
  410. }
  411. node, ok := nodes[c.NodeName]
  412. if !ok {
  413. log.Debugf("Node \"%s\" has been deleted from Kubernetes. Query historical data to get it.", c.NodeName)
  414. if n, ok := missingNodes[c.NodeName]; ok {
  415. node = n
  416. } else {
  417. node = &costAnalyzerCloud.Node{}
  418. missingNodes[c.NodeName] = node
  419. }
  420. }
  421. namespacelabels := namespaceLabelsMapping[c.Namespace+","+c.ClusterID]
  422. namespaceAnnotations := namespaceAnnotationsMapping[c.Namespace+","+c.ClusterID]
  423. costs := &CostData{
  424. Name: c.ContainerName,
  425. PodName: c.PodName,
  426. NodeName: c.NodeName,
  427. NodeData: node,
  428. Namespace: c.Namespace,
  429. RAMReq: RAMReqV,
  430. RAMUsed: RAMUsedV,
  431. CPUReq: CPUReqV,
  432. CPUUsed: CPUUsedV,
  433. GPUReq: GPUReqV,
  434. Annotations: namespaceAnnotations,
  435. NamespaceLabels: namespacelabels,
  436. ClusterID: c.ClusterID,
  437. ClusterName: cm.ClusterMap.NameFor(c.ClusterID),
  438. }
  439. var cpuReq, cpuUse *util.Vector
  440. if len(costs.CPUReq) > 0 {
  441. cpuReq = costs.CPUReq[0]
  442. }
  443. if len(costs.CPUUsed) > 0 {
  444. cpuUse = costs.CPUUsed[0]
  445. }
  446. costs.CPUAllocation = getContainerAllocation(cpuReq, cpuUse, "CPU")
  447. var ramReq, ramUse *util.Vector
  448. if len(costs.RAMReq) > 0 {
  449. ramReq = costs.RAMReq[0]
  450. }
  451. if len(costs.RAMUsed) > 0 {
  452. ramUse = costs.RAMUsed[0]
  453. }
  454. costs.RAMAllocation = getContainerAllocation(ramReq, ramUse, "RAM")
  455. containerNameCost[key] = costs
  456. missingContainers[key] = costs
  457. }
  458. }
  459. // Use unmounted pvs to create a mapping of "Unmounted-<Namespace>" containers
  460. // to pass along the cost data
  461. unmounted := findUnmountedPVCostData(cm.ClusterMap, unmountedPVs, namespaceLabelsMapping, namespaceAnnotationsMapping)
  462. for k, costs := range unmounted {
  463. log.Debugf("Unmounted PVs in Namespace/ClusterID: %s/%s", costs.Namespace, costs.ClusterID)
  464. containerNameCost[k] = costs
  465. }
  466. err = findDeletedNodeInfo(cm.DataSource, missingNodes, start, end)
  467. if err != nil {
  468. log.Errorf("Error fetching historical node data: %s", err.Error())
  469. }
  470. err = findDeletedPodInfo(cm.DataSource, missingContainers, start, end)
  471. if err != nil {
  472. log.Errorf("Error fetching historical pod data: %s", err.Error())
  473. }
  474. return containerNameCost, err
  475. }
  476. func queryMetrics(mq source.MetricsQuerier, start, end time.Time) ([]*source.ContainerMetricResult, []*source.ContainerMetricResult, []*source.NetZoneGiBResult, []*source.NetRegionGiBResult, []*source.NetInternetGiBResult, error) {
  477. grp := source.NewQueryGroup()
  478. resChRAMUsage := source.WithGroup(grp, mq.QueryRAMUsageAvg(start, end))
  479. resChCPUUsage := source.WithGroup(grp, mq.QueryCPUUsageAvg(start, end))
  480. resChNetZoneRequests := source.WithGroup(grp, mq.QueryNetZoneGiB(start, end))
  481. resChNetRegionRequests := source.WithGroup(grp, mq.QueryNetRegionGiB(start, end))
  482. resChNetInternetRequests := source.WithGroup(grp, mq.QueryNetInternetGiB(start, end))
  483. // Process metrics query results. Handle errors using ctx.Errors.
  484. resRAMUsage, _ := resChRAMUsage.Await()
  485. resCPUUsage, _ := resChCPUUsage.Await()
  486. resNetZoneRequests, _ := resChNetZoneRequests.Await()
  487. resNetRegionRequests, _ := resChNetRegionRequests.Await()
  488. resNetInternetRequests, _ := resChNetInternetRequests.Await()
  489. // NOTE: The way we currently handle errors and warnings only early returns if there is an error. Warnings
  490. // NOTE: will not propagate unless coupled with errors.
  491. if grp.HasErrors() {
  492. // To keep the context of where the errors are occurring, we log the errors here and pass them the error
  493. // back to the caller. The caller should handle the specific case where error is an ErrorCollection
  494. for _, queryErr := range grp.Errors() {
  495. if queryErr.Error != nil {
  496. log.Errorf("ComputeCostData: Request Error: %s", queryErr.Error)
  497. }
  498. if queryErr.ParseError != nil {
  499. log.Errorf("ComputeCostData: Parsing Error: %s", queryErr.ParseError)
  500. }
  501. }
  502. // ErrorCollection is an collection of errors wrapped in a single error implementation
  503. // We opt to not return an error for the sake of running as a pure exporter.
  504. return resRAMUsage, resCPUUsage, resNetZoneRequests, resNetRegionRequests, resNetInternetRequests, grp.Error()
  505. }
  506. return resRAMUsage, resCPUUsage, resNetZoneRequests, resNetRegionRequests, resNetInternetRequests, nil
  507. }
  508. func findUnmountedPVCostData(clusterMap clusters.ClusterMap, unmountedPVs map[string][]*PersistentVolumeClaimData, namespaceLabelsMapping map[string]map[string]string, namespaceAnnotationsMapping map[string]map[string]string) map[string]*CostData {
  509. costs := make(map[string]*CostData)
  510. if len(unmountedPVs) == 0 {
  511. return costs
  512. }
  513. for k, pv := range unmountedPVs {
  514. keyParts := strings.Split(k, ",")
  515. if len(keyParts) != 3 {
  516. log.Warnf("Unmounted PV used key with incorrect parts: %s", k)
  517. continue
  518. }
  519. ns, _, clusterID := keyParts[0], keyParts[1], keyParts[2]
  520. namespacelabels := namespaceLabelsMapping[ns+","+clusterID]
  521. namespaceAnnotations := namespaceAnnotationsMapping[ns+","+clusterID]
  522. metric := NewContainerMetricFromValues(ns, unmountedPVsContainer, unmountedPVsContainer, "", clusterID)
  523. key := metric.Key()
  524. if costData, ok := costs[key]; !ok {
  525. costs[key] = &CostData{
  526. Name: unmountedPVsContainer,
  527. PodName: unmountedPVsContainer,
  528. NodeName: "",
  529. Annotations: namespaceAnnotations,
  530. Namespace: ns,
  531. NamespaceLabels: namespacelabels,
  532. Labels: namespacelabels,
  533. ClusterID: clusterID,
  534. ClusterName: clusterMap.NameFor(clusterID),
  535. PVCData: pv,
  536. }
  537. } else {
  538. costData.PVCData = append(costData.PVCData, pv...)
  539. }
  540. }
  541. return costs
  542. }
  543. func findDeletedPodInfo(dataSource source.OpenCostDataSource, missingContainers map[string]*CostData, start, end time.Time) error {
  544. if len(missingContainers) > 0 {
  545. mq := dataSource.Metrics()
  546. podLabelsResCh := mq.QueryPodLabels(start, end)
  547. podLabelsResult, err := podLabelsResCh.Await()
  548. if err != nil {
  549. log.Errorf("failed to parse historical pod labels: %s", err.Error())
  550. }
  551. podLabels := make(map[string]map[string]string)
  552. if podLabelsResult != nil {
  553. podLabels, err = parsePodLabels(podLabelsResult)
  554. if err != nil {
  555. log.Errorf("failed to parse historical pod labels: %s", err.Error())
  556. }
  557. }
  558. for key, costData := range missingContainers {
  559. cm, _ := NewContainerMetricFromKey(key)
  560. labels, ok := podLabels[cm.PodName]
  561. if !ok {
  562. labels = make(map[string]string)
  563. }
  564. for k, v := range costData.NamespaceLabels {
  565. labels[k] = v
  566. }
  567. costData.Labels = labels
  568. }
  569. }
  570. return nil
  571. }
  572. func findDeletedNodeInfo(dataSource source.OpenCostDataSource, missingNodes map[string]*costAnalyzerCloud.Node, start, end time.Time) error {
  573. if len(missingNodes) > 0 {
  574. defer measureTime(time.Now(), profileThreshold, "Finding Deleted Node Info")
  575. grp := source.NewQueryGroup()
  576. mq := dataSource.Metrics()
  577. cpuCostResCh := source.WithGroup(grp, mq.QueryNodeCPUPricePerHr(start, end))
  578. ramCostResCh := source.WithGroup(grp, mq.QueryNodeRAMPricePerGiBHr(start, end))
  579. gpuCostResCh := source.WithGroup(grp, mq.QueryNodeGPUPricePerHr(start, end))
  580. cpuCostRes, _ := cpuCostResCh.Await()
  581. ramCostRes, _ := ramCostResCh.Await()
  582. gpuCostRes, _ := gpuCostResCh.Await()
  583. if grp.HasErrors() {
  584. return grp.Error()
  585. }
  586. cpuCosts, err := getCost(cpuCostRes, cpuCostNode, cpuCostData)
  587. if err != nil {
  588. return err
  589. }
  590. ramCosts, err := getCost(ramCostRes, ramCostNode, ramCostData)
  591. if err != nil {
  592. return err
  593. }
  594. gpuCosts, err := getCost(gpuCostRes, gpuCostNode, gpuCostData)
  595. if err != nil {
  596. return err
  597. }
  598. if len(cpuCosts) == 0 {
  599. log.Infof("Opencost metrics not currently available. Ingest this server's /metrics endpoint to get that data.")
  600. }
  601. for node, costv := range cpuCosts {
  602. if _, ok := missingNodes[node]; ok {
  603. missingNodes[node].VCPUCost = fmt.Sprintf("%f", costv[0].Value)
  604. } else {
  605. log.DedupedWarningf(5, "Node `%s` in metrics but not k8s api", node)
  606. }
  607. }
  608. for node, costv := range ramCosts {
  609. if _, ok := missingNodes[node]; ok {
  610. missingNodes[node].RAMCost = fmt.Sprintf("%f", costv[0].Value)
  611. }
  612. }
  613. for node, costv := range gpuCosts {
  614. if _, ok := missingNodes[node]; ok {
  615. missingNodes[node].GPUCost = fmt.Sprintf("%f", costv[0].Value)
  616. }
  617. }
  618. }
  619. return nil
  620. }
  621. // getContainerAllocation takes the max between request and usage. This function
  622. // returns a slice containing a single element describing the container's
  623. // allocation.
  624. //
  625. // Additionally, the timestamp of the allocation will be the highest value
  626. // timestamp between the two vectors. This mitigates situations where
  627. // Timestamp=0. This should have no effect on the metrics emitted by the
  628. // CostModelMetricsEmitter
  629. func getContainerAllocation(req *util.Vector, used *util.Vector, allocationType string) []*util.Vector {
  630. var result []*util.Vector
  631. if req != nil && used != nil {
  632. x1 := req.Value
  633. if math.IsNaN(x1) {
  634. log.Debugf("NaN value found during %s allocation calculation for requests.", allocationType)
  635. x1 = 0.0
  636. }
  637. y1 := used.Value
  638. if math.IsNaN(y1) {
  639. log.Debugf("NaN value found during %s allocation calculation for used.", allocationType)
  640. y1 = 0.0
  641. }
  642. result = []*util.Vector{
  643. {
  644. Value: math.Max(x1, y1),
  645. Timestamp: math.Max(req.Timestamp, used.Timestamp),
  646. },
  647. }
  648. if result[0].Value == 0 && result[0].Timestamp == 0 {
  649. log.Debugf("No request or usage data found during %s allocation calculation. Setting allocation to 0.", allocationType)
  650. }
  651. } else if req != nil {
  652. result = []*util.Vector{
  653. {
  654. Value: req.Value,
  655. Timestamp: req.Timestamp,
  656. },
  657. }
  658. } else if used != nil {
  659. result = []*util.Vector{
  660. {
  661. Value: used.Value,
  662. Timestamp: used.Timestamp,
  663. },
  664. }
  665. } else {
  666. log.Debugf("No request or usage data found during %s allocation calculation. Setting allocation to 0.", allocationType)
  667. result = []*util.Vector{
  668. {
  669. Value: 0,
  670. Timestamp: float64(time.Now().UTC().Unix()),
  671. },
  672. }
  673. }
  674. return result
  675. }
  676. func (cm *CostModel) addPVData(pvClaimMapping map[string]*PersistentVolumeClaimData) error {
  677. cache := cm.Cache
  678. cloud := cm.Provider
  679. cfg, err := cloud.GetConfig()
  680. if err != nil {
  681. return err
  682. }
  683. // Pull a region from the first node
  684. var defaultRegion string
  685. nodeList := cache.GetAllNodes()
  686. if len(nodeList) > 0 {
  687. defaultRegion, _ = util.GetRegion(nodeList[0].Labels)
  688. }
  689. storageClasses := cache.GetAllStorageClasses()
  690. storageClassMap := make(map[string]map[string]string)
  691. for _, storageClass := range storageClasses {
  692. params := storageClass.Parameters
  693. storageClassMap[storageClass.Name] = params
  694. if storageClass.Annotations["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.Annotations["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  695. storageClassMap["default"] = params
  696. storageClassMap[""] = params
  697. }
  698. }
  699. pvs := cache.GetAllPersistentVolumes()
  700. pvMap := make(map[string]*costAnalyzerCloud.PV)
  701. for _, pv := range pvs {
  702. parameters, ok := storageClassMap[pv.Spec.StorageClassName]
  703. if !ok {
  704. log.Debugf("Unable to find parameters for storage class \"%s\". Does pv \"%s\" have a storageClassName?", pv.Spec.StorageClassName, pv.Name)
  705. }
  706. var region string
  707. if r, ok := util.GetRegion(pv.Labels); ok {
  708. region = r
  709. } else {
  710. region = defaultRegion
  711. }
  712. cacPv := &costAnalyzerCloud.PV{
  713. Class: pv.Spec.StorageClassName,
  714. Region: region,
  715. Parameters: parameters,
  716. }
  717. err := cm.GetPVCost(cacPv, pv, region)
  718. if err != nil {
  719. return err
  720. }
  721. pvMap[pv.Name] = cacPv
  722. }
  723. for _, pvc := range pvClaimMapping {
  724. if vol, ok := pvMap[pvc.VolumeName]; ok {
  725. pvc.Volume = vol
  726. } else {
  727. log.Debugf("PV not found, using default")
  728. pvc.Volume = &costAnalyzerCloud.PV{
  729. Cost: cfg.Storage,
  730. }
  731. }
  732. }
  733. return nil
  734. }
  735. func (cm *CostModel) GetPVCost(pv *costAnalyzerCloud.PV, kpv *clustercache.PersistentVolume, defaultRegion string) error {
  736. cp := cm.Provider
  737. cfg, err := cp.GetConfig()
  738. if err != nil {
  739. return err
  740. }
  741. key := cp.GetPVKey(kpv, pv.Parameters, defaultRegion)
  742. pv.ProviderID = key.ID()
  743. pvWithCost, err := cp.PVPricing(key)
  744. if err != nil {
  745. pv.Cost = cfg.Storage
  746. return err
  747. }
  748. if pvWithCost == nil || pvWithCost.Cost == "" {
  749. pv.Cost = cfg.Storage
  750. return nil // set default cost
  751. }
  752. pv.Cost = pvWithCost.Cost
  753. return nil
  754. }
  755. func (cm *CostModel) GetPricingSourceCounts() (*costAnalyzerCloud.PricingMatchMetadata, error) {
  756. if cm.pricingMetadata != nil {
  757. return cm.pricingMetadata, nil
  758. } else {
  759. return nil, fmt.Errorf("Node costs not yet calculated")
  760. }
  761. }
  762. func (cm *CostModel) GetNodeCost() (map[string]*costAnalyzerCloud.Node, error) {
  763. cp := cm.Provider
  764. cfg, err := cp.GetConfig()
  765. if err != nil {
  766. return nil, err
  767. }
  768. nodeList := cm.Cache.GetAllNodes()
  769. nodes := make(map[string]*costAnalyzerCloud.Node)
  770. pmd := &costAnalyzerCloud.PricingMatchMetadata{
  771. TotalNodes: 0,
  772. PricingTypeCounts: make(map[costAnalyzerCloud.PricingType]int),
  773. }
  774. for _, n := range nodeList {
  775. name := n.Name
  776. nodeLabels := n.Labels
  777. nodeLabels["providerID"] = n.SpecProviderID
  778. pmd.TotalNodes++
  779. cnode, _, err := cp.NodePricing(cp.GetKey(nodeLabels, n))
  780. if err != nil {
  781. log.Infof("Could not get node pricing for node %s. Falling back to default pricing", name)
  782. log.Debugf("Error getting node pricing: %s", err.Error())
  783. if cnode != nil {
  784. nodes[name] = cnode
  785. continue
  786. } else {
  787. cnode = &costAnalyzerCloud.Node{
  788. VCPUCost: cfg.CPU,
  789. RAMCost: cfg.RAM,
  790. }
  791. }
  792. }
  793. pmd.PricingTypeCounts[cnode.PricingType]++
  794. // newCnode builds upon cnode but populates/overrides certain fields.
  795. // cnode was populated leveraging cloud provider public pricing APIs.
  796. newCnode := *cnode
  797. if newCnode.InstanceType == "" {
  798. it, _ := util.GetInstanceType(n.Labels)
  799. newCnode.InstanceType = it
  800. }
  801. if newCnode.Region == "" {
  802. region, _ := util.GetRegion(n.Labels)
  803. newCnode.Region = region
  804. }
  805. if newCnode.ArchType == "" {
  806. arch, _ := util.GetArchType(n.Labels)
  807. newCnode.ArchType = arch
  808. }
  809. newCnode.ProviderID = n.SpecProviderID
  810. var cpu float64
  811. if newCnode.VCPU == "" {
  812. cpu = float64(n.Status.Capacity.Cpu().Value())
  813. newCnode.VCPU = n.Status.Capacity.Cpu().String()
  814. } else {
  815. cpu, err = strconv.ParseFloat(newCnode.VCPU, 64)
  816. if err != nil {
  817. log.Warnf("parsing VCPU value: \"%s\" as float64", newCnode.VCPU)
  818. }
  819. }
  820. if math.IsNaN(cpu) {
  821. log.Warnf("cpu parsed as NaN. Setting to 0.")
  822. cpu = 0
  823. }
  824. var ram float64
  825. if newCnode.RAM == "" {
  826. newCnode.RAM = n.Status.Capacity.Memory().String()
  827. }
  828. ram = float64(n.Status.Capacity.Memory().Value())
  829. if math.IsNaN(ram) {
  830. log.Warnf("ram parsed as NaN. Setting to 0.")
  831. ram = 0
  832. }
  833. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  834. gpuc, err := strconv.ParseFloat(newCnode.GPU, 64)
  835. if err != nil {
  836. gpuc = 0.0
  837. }
  838. // The k8s API will often report more accurate results for GPU count
  839. // than cloud provider public pricing APIs. If found, override the
  840. // original value.
  841. gpuOverride, vgpuOverride, err := getGPUCount(cm.Cache, n)
  842. if err != nil {
  843. log.Warnf("Unable to get GPUCount for node %s: %s", n.Name, err.Error())
  844. }
  845. if gpuOverride > 0 {
  846. newCnode.GPU = fmt.Sprintf("%f", gpuOverride)
  847. gpuc = gpuOverride
  848. }
  849. if vgpuOverride > 0 {
  850. newCnode.VGPU = fmt.Sprintf("%f", vgpuOverride)
  851. }
  852. // Special case for SUSE rancher, since it won't behave with normal
  853. // calculations, courtesy of the instance type not being "real" (a
  854. // recognizable AWS instance type.)
  855. if newCnode.InstanceType == "rke2" {
  856. log.Infof(
  857. "Found a SUSE Rancher node %s, defaulting and skipping math",
  858. cp.GetKey(nodeLabels, n).Features(),
  859. )
  860. defaultCPUCorePrice, err := strconv.ParseFloat(cfg.CPU, 64)
  861. if err != nil {
  862. log.Errorf("Could not parse default cpu price")
  863. defaultCPUCorePrice = 0
  864. }
  865. if math.IsNaN(defaultCPUCorePrice) {
  866. log.Warnf("defaultCPU parsed as NaN. Setting to 0.")
  867. defaultCPUCorePrice = 0
  868. }
  869. // Some customers may want GPU pricing to be determined by the labels affixed to their nodes. GpuPricing
  870. // passes the node's labels to the provider, which then cross-references them with the labels that the
  871. // provider knows to have label-specific costs associated with them, and returns that cost. See CSVProvider
  872. // for an example implementation.
  873. var gpuPrice float64
  874. gpuPricing, err := cp.GpuPricing(nodeLabels)
  875. if err != nil {
  876. log.Errorf("Could not determine custom GPU pricing: %s", err)
  877. gpuPrice = 0
  878. } else if len(gpuPricing) > 0 {
  879. gpuPrice, err = strconv.ParseFloat(gpuPricing, 64)
  880. if err != nil {
  881. log.Errorf("Could not parse custom GPU pricing: %s", err)
  882. gpuPrice = 0
  883. } else if math.IsNaN(gpuPrice) {
  884. log.Warnf("Custom GPU pricing parsed as NaN. Setting to 0.")
  885. gpuPrice = 0
  886. } else {
  887. log.Infof("Using custom GPU pricing for node \"%s\": %f", name, gpuPrice)
  888. }
  889. } else {
  890. gpuPrice, err = strconv.ParseFloat(cfg.GPU, 64)
  891. if err != nil {
  892. log.Errorf("Could not parse default gpu price")
  893. gpuPrice = 0
  894. }
  895. if math.IsNaN(gpuPrice) {
  896. log.Warnf("defaultGPU parsed as NaN. Setting to 0.")
  897. gpuPrice = 0
  898. }
  899. }
  900. defaultRAMPrice, err := strconv.ParseFloat(cfg.RAM, 64)
  901. if err != nil {
  902. log.Errorf("Could not parse default ram price")
  903. defaultRAMPrice = 0
  904. }
  905. if math.IsNaN(defaultRAMPrice) {
  906. log.Warnf("defaultRAM parsed as NaN. Setting to 0.")
  907. defaultRAMPrice = 0
  908. }
  909. defaultGPUPrice, err := strconv.ParseFloat(cfg.GPU, 64)
  910. if err != nil {
  911. log.Errorf("Could not parse default gpu price")
  912. defaultGPUPrice = 0
  913. }
  914. if math.IsNaN(defaultGPUPrice) {
  915. log.Warnf("defaultGPU parsed as NaN. Setting to 0.")
  916. defaultGPUPrice = 0
  917. }
  918. // Just say no to doing the ratios!
  919. cpuCost := defaultCPUCorePrice * cpu
  920. gpuCost := gpuPrice * gpuc
  921. ramCost := defaultRAMPrice * ram
  922. nodeCost := cpuCost + gpuCost + ramCost
  923. newCnode.Cost = fmt.Sprintf("%f", nodeCost)
  924. newCnode.VCPUCost = fmt.Sprintf("%f", defaultCPUCorePrice)
  925. newCnode.GPUCost = fmt.Sprintf("%f", gpuPrice)
  926. newCnode.RAMCost = fmt.Sprintf("%f", defaultRAMPrice)
  927. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  928. } else if newCnode.GPU != "" && newCnode.GPUCost == "" {
  929. // was the big thing to investigate. All the funky ratio math
  930. // we were doing was messing with their default pricing. for SUSE Rancher.
  931. // We reach this when a GPU is detected on a node, but no cost for
  932. // the GPU is defined in the OnDemand pricing. Calculate ratios of
  933. // CPU to RAM and GPU to RAM costs, then distribute the total node
  934. // cost among the CPU, RAM, and GPU.
  935. log.Tracef("GPU without cost found for %s, calculating...", cp.GetKey(nodeLabels, n).Features())
  936. // Some customers may want GPU pricing to be determined by the labels affixed to their nodes. GpuPricing
  937. // passes the node's labels to the provider, which then cross-references them with the labels that the
  938. // provider knows to have label-specific costs associated with them, and returns that cost. See CSVProvider
  939. // for an example implementation.
  940. gpuPricing, err := cp.GpuPricing(nodeLabels)
  941. if err != nil {
  942. log.Errorf("Could not determine custom GPU pricing: %s", err)
  943. } else if len(gpuPricing) > 0 {
  944. newCnode.GPUCost = gpuPricing
  945. log.Infof("Using custom GPU pricing for node \"%s\": %s", name, gpuPricing)
  946. }
  947. if newCnode.GPUCost == "" {
  948. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  949. if err != nil {
  950. log.Errorf("Could not parse default cpu price")
  951. defaultCPU = 0
  952. }
  953. if math.IsNaN(defaultCPU) {
  954. log.Warnf("defaultCPU parsed as NaN. Setting to 0.")
  955. defaultCPU = 0
  956. }
  957. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  958. if err != nil {
  959. log.Errorf("Could not parse default ram price")
  960. defaultRAM = 0
  961. }
  962. if math.IsNaN(defaultRAM) {
  963. log.Warnf("defaultRAM parsed as NaN. Setting to 0.")
  964. defaultRAM = 0
  965. }
  966. defaultGPU, err := strconv.ParseFloat(cfg.GPU, 64)
  967. if err != nil {
  968. log.Errorf("Could not parse default gpu price")
  969. defaultGPU = 0
  970. }
  971. if math.IsNaN(defaultGPU) {
  972. log.Warnf("defaultGPU parsed as NaN. Setting to 0.")
  973. defaultGPU = 0
  974. }
  975. cpuToRAMRatio := defaultCPU / defaultRAM
  976. if math.IsNaN(cpuToRAMRatio) {
  977. log.Warnf("cpuToRAMRatio[defaultCPU: %f / defaultRAM: %f] is NaN. Setting to 10.", defaultCPU, defaultRAM)
  978. cpuToRAMRatio = 10
  979. }
  980. gpuToRAMRatio := defaultGPU / defaultRAM
  981. if math.IsNaN(gpuToRAMRatio) {
  982. log.Warnf("gpuToRAMRatio is NaN. Setting to 100.")
  983. gpuToRAMRatio = 100
  984. }
  985. ramGB := ram / 1024 / 1024 / 1024
  986. if math.IsNaN(ramGB) {
  987. log.Warnf("ramGB is NaN. Setting to 0.")
  988. ramGB = 0
  989. }
  990. ramMultiple := gpuc*gpuToRAMRatio + cpu*cpuToRAMRatio + ramGB
  991. if math.IsNaN(ramMultiple) {
  992. log.Warnf("ramMultiple is NaN. Setting to 0.")
  993. ramMultiple = 0
  994. }
  995. var nodePrice float64
  996. if newCnode.Cost != "" {
  997. nodePrice, err = strconv.ParseFloat(newCnode.Cost, 64)
  998. if err != nil {
  999. log.Errorf("Could not parse total node price")
  1000. return nil, err
  1001. }
  1002. } else if newCnode.VCPUCost != "" {
  1003. nodePrice, err = strconv.ParseFloat(newCnode.VCPUCost, 64) // all the price was allocated to the CPU
  1004. if err != nil {
  1005. log.Errorf("Could not parse node vcpu price")
  1006. return nil, err
  1007. }
  1008. } else { // add case to use default pricing model when API data fails.
  1009. log.Debugf("No node price or CPUprice found, falling back to default")
  1010. nodePrice = defaultCPU*cpu + defaultRAM*ram + gpuc*defaultGPU
  1011. }
  1012. if math.IsNaN(nodePrice) {
  1013. log.Warnf("nodePrice parsed as NaN. Setting to 0.")
  1014. nodePrice = 0
  1015. }
  1016. ramPrice := (nodePrice / ramMultiple)
  1017. if math.IsNaN(ramPrice) {
  1018. log.Warnf("ramPrice[nodePrice: %f / ramMultiple: %f] parsed as NaN. Setting to 0.", nodePrice, ramMultiple)
  1019. ramPrice = 0
  1020. }
  1021. cpuPrice := ramPrice * cpuToRAMRatio
  1022. gpuPrice := ramPrice * gpuToRAMRatio
  1023. newCnode.VCPUCost = fmt.Sprintf("%f", cpuPrice)
  1024. newCnode.RAMCost = fmt.Sprintf("%f", ramPrice)
  1025. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  1026. newCnode.GPUCost = fmt.Sprintf("%f", gpuPrice)
  1027. }
  1028. } else if newCnode.RAMCost == "" {
  1029. // We reach this when no RAM cost is defined in the OnDemand
  1030. // pricing. It calculates a cpuToRAMRatio and ramMultiple to
  1031. // distrubte the total node cost among CPU and RAM costs.
  1032. log.Tracef("No RAM cost found for %s, calculating...", cp.GetKey(nodeLabels, n).Features())
  1033. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  1034. if err != nil {
  1035. log.Warnf("Could not parse default cpu price")
  1036. defaultCPU = 0
  1037. }
  1038. if math.IsNaN(defaultCPU) {
  1039. log.Warnf("defaultCPU parsed as NaN. Setting to 0.")
  1040. defaultCPU = 0
  1041. }
  1042. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  1043. if err != nil {
  1044. log.Warnf("Could not parse default ram price")
  1045. defaultRAM = 0
  1046. }
  1047. if math.IsNaN(defaultRAM) {
  1048. log.Warnf("defaultRAM parsed as NaN. Setting to 0.")
  1049. defaultRAM = 0
  1050. }
  1051. cpuToRAMRatio := defaultCPU / defaultRAM
  1052. if math.IsNaN(cpuToRAMRatio) {
  1053. log.Warnf("cpuToRAMRatio[defaultCPU: %f / defaultRAM: %f] is NaN. Setting to 10.", defaultCPU, defaultRAM)
  1054. cpuToRAMRatio = 10
  1055. }
  1056. ramGB := ram / 1024 / 1024 / 1024
  1057. if math.IsNaN(ramGB) {
  1058. log.Warnf("ramGB is NaN. Setting to 0.")
  1059. ramGB = 0
  1060. }
  1061. ramMultiple := cpu*cpuToRAMRatio + ramGB
  1062. if math.IsNaN(ramMultiple) {
  1063. log.Warnf("ramMultiple is NaN. Setting to 0.")
  1064. ramMultiple = 0
  1065. }
  1066. var nodePrice float64
  1067. if newCnode.Cost != "" {
  1068. nodePrice, err = strconv.ParseFloat(newCnode.Cost, 64)
  1069. if err != nil {
  1070. log.Warnf("Could not parse total node price")
  1071. return nil, err
  1072. }
  1073. if newCnode.GPUCost != "" {
  1074. gpuPrice, err := strconv.ParseFloat(newCnode.GPUCost, 64)
  1075. if err != nil {
  1076. log.Warnf("Could not parse node gpu price")
  1077. return nil, err
  1078. }
  1079. nodePrice = nodePrice - gpuPrice // remove the gpuPrice from the total, we're just costing out RAM and CPU.
  1080. }
  1081. } else if newCnode.VCPUCost != "" {
  1082. nodePrice, err = strconv.ParseFloat(newCnode.VCPUCost, 64) // all the price was allocated to the CPU
  1083. if err != nil {
  1084. log.Warnf("Could not parse node vcpu price")
  1085. return nil, err
  1086. }
  1087. } else { // add case to use default pricing model when API data fails.
  1088. log.Debugf("No node price or CPUprice found, falling back to default")
  1089. nodePrice = defaultCPU*cpu + defaultRAM*ramGB
  1090. }
  1091. if math.IsNaN(nodePrice) {
  1092. log.Warnf("nodePrice parsed as NaN. Setting to 0.")
  1093. nodePrice = 0
  1094. }
  1095. ramPrice := (nodePrice / ramMultiple)
  1096. if math.IsNaN(ramPrice) {
  1097. log.Warnf("ramPrice[nodePrice: %f / ramMultiple: %f] parsed as NaN. Setting to 0.", nodePrice, ramMultiple)
  1098. ramPrice = 0
  1099. }
  1100. cpuPrice := ramPrice * cpuToRAMRatio
  1101. if defaultRAM != 0 {
  1102. newCnode.VCPUCost = fmt.Sprintf("%f", cpuPrice)
  1103. newCnode.RAMCost = fmt.Sprintf("%f", ramPrice)
  1104. } else { // just assign the full price to CPU
  1105. if cpu != 0 {
  1106. newCnode.VCPUCost = fmt.Sprintf("%f", nodePrice/cpu)
  1107. } else {
  1108. newCnode.VCPUCost = fmt.Sprintf("%f", nodePrice)
  1109. }
  1110. }
  1111. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  1112. log.Tracef("Computed \"%s\" RAM Cost := %v", name, newCnode.RAMCost)
  1113. }
  1114. nodes[name] = &newCnode
  1115. }
  1116. cm.pricingMetadata = pmd
  1117. cp.ApplyReservedInstancePricing(nodes)
  1118. return nodes, nil
  1119. }
  1120. // TODO: drop some logs
  1121. func (cm *CostModel) GetLBCost() (map[serviceKey]*costAnalyzerCloud.LoadBalancer, error) {
  1122. // for fetching prices from cloud provider
  1123. // cfg, err := cp.GetConfig()
  1124. // if err != nil {
  1125. // return nil, err
  1126. // }
  1127. cp := cm.Provider
  1128. servicesList := cm.Cache.GetAllServices()
  1129. loadBalancerMap := make(map[serviceKey]*costAnalyzerCloud.LoadBalancer)
  1130. for _, service := range servicesList {
  1131. namespace := service.Namespace
  1132. name := service.Name
  1133. key := serviceKey{
  1134. Cluster: coreenv.GetClusterID(),
  1135. Namespace: namespace,
  1136. Service: name,
  1137. }
  1138. if service.Type == "LoadBalancer" {
  1139. loadBalancer, err := cp.LoadBalancerPricing()
  1140. if err != nil {
  1141. return nil, err
  1142. }
  1143. newLoadBalancer := *loadBalancer
  1144. for _, loadBalancerIngress := range service.Status.LoadBalancer.Ingress {
  1145. address := loadBalancerIngress.IP
  1146. // Some cloud providers use hostname rather than IP
  1147. if address == "" {
  1148. address = loadBalancerIngress.Hostname
  1149. }
  1150. newLoadBalancer.IngressIPAddresses = append(newLoadBalancer.IngressIPAddresses, address)
  1151. }
  1152. loadBalancerMap[key] = &newLoadBalancer
  1153. }
  1154. }
  1155. return loadBalancerMap, nil
  1156. }
  1157. func getPodServices(cache clustercache.ClusterCache, podList []*clustercache.Pod, clusterID string) (map[string]map[string][]string, error) {
  1158. servicesList := cache.GetAllServices()
  1159. podServicesMapping := make(map[string]map[string][]string)
  1160. for _, service := range servicesList {
  1161. namespace := service.Namespace
  1162. name := service.Name
  1163. key := namespace + "," + clusterID
  1164. if _, ok := podServicesMapping[key]; !ok {
  1165. podServicesMapping[key] = make(map[string][]string)
  1166. }
  1167. s := labels.Nothing()
  1168. if len(service.SpecSelector) > 0 {
  1169. s = labels.Set(service.SpecSelector).AsSelectorPreValidated()
  1170. }
  1171. for _, pod := range podList {
  1172. labelSet := labels.Set(pod.Labels)
  1173. if s.Matches(labelSet) && pod.Namespace == namespace {
  1174. services, ok := podServicesMapping[key][pod.Name]
  1175. if ok {
  1176. podServicesMapping[key][pod.Name] = append(services, name)
  1177. } else {
  1178. podServicesMapping[key][pod.Name] = []string{name}
  1179. }
  1180. }
  1181. }
  1182. }
  1183. return podServicesMapping, nil
  1184. }
  1185. func getPodStatefulsets(cache clustercache.ClusterCache, podList []*clustercache.Pod, clusterID string) (map[string]map[string][]string, error) {
  1186. ssList := cache.GetAllStatefulSets()
  1187. podSSMapping := make(map[string]map[string][]string) // namespace: podName: [deploymentNames]
  1188. for _, ss := range ssList {
  1189. namespace := ss.Namespace
  1190. name := ss.Name
  1191. key := namespace + "," + clusterID
  1192. if _, ok := podSSMapping[key]; !ok {
  1193. podSSMapping[key] = make(map[string][]string)
  1194. }
  1195. s, err := metav1.LabelSelectorAsSelector(ss.SpecSelector)
  1196. if err != nil {
  1197. log.Errorf("Error doing deployment label conversion: %s", err.Error())
  1198. }
  1199. for _, pod := range podList {
  1200. labelSet := labels.Set(pod.Labels)
  1201. if s.Matches(labelSet) && pod.Namespace == namespace {
  1202. sss, ok := podSSMapping[key][pod.Name]
  1203. if ok {
  1204. podSSMapping[key][pod.Name] = append(sss, name)
  1205. } else {
  1206. podSSMapping[key][pod.Name] = []string{name}
  1207. }
  1208. }
  1209. }
  1210. }
  1211. return podSSMapping, nil
  1212. }
  1213. func getPodDeployments(cache clustercache.ClusterCache, podList []*clustercache.Pod, clusterID string) (map[string]map[string][]string, error) {
  1214. deploymentsList := cache.GetAllDeployments()
  1215. podDeploymentsMapping := make(map[string]map[string][]string) // namespace: podName: [deploymentNames]
  1216. for _, deployment := range deploymentsList {
  1217. namespace := deployment.Namespace
  1218. name := deployment.Name
  1219. key := namespace + "," + clusterID
  1220. if _, ok := podDeploymentsMapping[key]; !ok {
  1221. podDeploymentsMapping[key] = make(map[string][]string)
  1222. }
  1223. s, err := metav1.LabelSelectorAsSelector(deployment.SpecSelector)
  1224. if err != nil {
  1225. log.Errorf("Error doing deployment label conversion: %s", err)
  1226. }
  1227. for _, pod := range podList {
  1228. labelSet := labels.Set(pod.Labels)
  1229. if s.Matches(labelSet) && pod.Namespace == namespace {
  1230. deployments, ok := podDeploymentsMapping[key][pod.Name]
  1231. if ok {
  1232. podDeploymentsMapping[key][pod.Name] = append(deployments, name)
  1233. } else {
  1234. podDeploymentsMapping[key][pod.Name] = []string{name}
  1235. }
  1236. }
  1237. }
  1238. }
  1239. return podDeploymentsMapping, nil
  1240. }
  1241. func getNamespaceLabels(cache clustercache.ClusterCache, clusterID string) (map[string]map[string]string, error) {
  1242. nsToLabels := make(map[string]map[string]string)
  1243. nss := cache.GetAllNamespaces()
  1244. for _, ns := range nss {
  1245. labels := make(map[string]string)
  1246. for k, v := range ns.Labels {
  1247. labels[promutil.SanitizeLabelName(k)] = v
  1248. }
  1249. nsToLabels[ns.Name+","+clusterID] = labels
  1250. }
  1251. return nsToLabels, nil
  1252. }
  1253. func getNamespaceAnnotations(cache clustercache.ClusterCache, clusterID string) (map[string]map[string]string, error) {
  1254. nsToAnnotations := make(map[string]map[string]string)
  1255. nss := cache.GetAllNamespaces()
  1256. for _, ns := range nss {
  1257. annotations := make(map[string]string)
  1258. for k, v := range ns.Annotations {
  1259. annotations[promutil.SanitizeLabelName(k)] = v
  1260. }
  1261. nsToAnnotations[ns.Name+","+clusterID] = annotations
  1262. }
  1263. return nsToAnnotations, nil
  1264. }
  1265. func getDaemonsetsOfPod(pod clustercache.Pod) []string {
  1266. for _, ownerReference := range pod.OwnerReferences {
  1267. if ownerReference.Kind == "DaemonSet" {
  1268. return []string{ownerReference.Name}
  1269. }
  1270. }
  1271. return []string{}
  1272. }
  1273. func getJobsOfPod(pod clustercache.Pod) []string {
  1274. for _, ownerReference := range pod.OwnerReferences {
  1275. if ownerReference.Kind == "Job" {
  1276. return []string{ownerReference.Name}
  1277. }
  1278. }
  1279. return []string{}
  1280. }
  1281. func getStatefulSetsOfPod(pod clustercache.Pod) []string {
  1282. for _, ownerReference := range pod.OwnerReferences {
  1283. if ownerReference.Kind == "StatefulSet" {
  1284. return []string{ownerReference.Name}
  1285. }
  1286. }
  1287. return []string{}
  1288. }
  1289. // getGPUCount reads the node's Status and Labels (via the k8s API) to identify
  1290. // the number of GPUs and vGPUs are equipped on the node. If unable to identify
  1291. // a GPU count, it will return -1.
  1292. func getGPUCount(cache clustercache.ClusterCache, n *clustercache.Node) (float64, float64, error) {
  1293. g, hasGpu := n.Status.Capacity["nvidia.com/gpu"]
  1294. _, hasReplicas := n.Labels["nvidia.com/gpu.replicas"]
  1295. // Case 1: Standard NVIDIA GPU
  1296. if hasGpu && g.Value() != 0 && !hasReplicas {
  1297. return float64(g.Value()), float64(g.Value()), nil
  1298. }
  1299. // Case 2: NVIDIA GPU with GPU Feature Discovery (GFD) Pod enabled.
  1300. // Ref: https://docs.nvidia.com/datacenter/cloud-native/gpu-operator/latest/gpu-sharing.html#verifying-the-gpu-time-slicing-configuration
  1301. // Ref: https://github.com/NVIDIA/k8s-device-plugin/blob/d899752a424818428f744a946d32b132ea2c0cf1/internal/lm/resource_test.go#L44-L45
  1302. // Ref: https://github.com/NVIDIA/k8s-device-plugin/blob/d899752a424818428f744a946d32b132ea2c0cf1/internal/lm/resource_test.go#L103-L118
  1303. if hasReplicas {
  1304. resultGPU := 0.0
  1305. resultVGPU := 0.0
  1306. if c, ok := n.Labels["nvidia.com/gpu.count"]; ok {
  1307. var err error
  1308. resultGPU, err = strconv.ParseFloat(c, 64)
  1309. if err != nil {
  1310. return -1, -1, fmt.Errorf("could not parse label \"nvidia.com/gpu.count\": %v", err)
  1311. }
  1312. }
  1313. if s, ok := n.Status.Capacity["nvidia.com/gpu.shared"]; ok { // GFD configured `renameByDefault=true`
  1314. resultVGPU = float64(s.Value())
  1315. } else if g, ok := n.Status.Capacity["nvidia.com/gpu"]; ok { // GFD configured `renameByDefault=false`
  1316. resultVGPU = float64(g.Value())
  1317. } else {
  1318. resultVGPU = resultGPU
  1319. }
  1320. return resultGPU, resultVGPU, nil
  1321. }
  1322. // Case 3: AWS vGPU
  1323. if vgpu, ok := n.Status.Capacity["k8s.amazonaws.com/vgpu"]; ok {
  1324. vgpuCount, err := getAllocatableVGPUs(cache)
  1325. if err != nil {
  1326. return -1, -1, err
  1327. }
  1328. vgpuCoeff := 10.0
  1329. if vgpuCount > 0.0 {
  1330. vgpuCoeff = vgpuCount
  1331. }
  1332. if vgpu.Value() != 0 {
  1333. resultGPU := float64(vgpu.Value()) / vgpuCoeff
  1334. resultVGPU := float64(vgpu.Value())
  1335. return resultGPU, resultVGPU, nil
  1336. }
  1337. }
  1338. // No GPU found
  1339. return -1, -1, nil
  1340. }
  1341. func getAllocatableVGPUs(cache clustercache.ClusterCache) (float64, error) {
  1342. daemonsets := cache.GetAllDaemonSets()
  1343. vgpuCount := 0.0
  1344. for _, ds := range daemonsets {
  1345. dsContainerList := &ds.SpecContainers
  1346. for _, ctnr := range *dsContainerList {
  1347. if ctnr.Args != nil {
  1348. for _, arg := range ctnr.Args {
  1349. if strings.Contains(arg, "--vgpu=") {
  1350. vgpus, err := strconv.ParseFloat(arg[strings.IndexByte(arg, '=')+1:], 64)
  1351. if err != nil {
  1352. log.Errorf("failed to parse vgpu allocation string %s: %v", arg, err)
  1353. continue
  1354. }
  1355. vgpuCount = vgpus
  1356. return vgpuCount, nil
  1357. }
  1358. }
  1359. }
  1360. }
  1361. }
  1362. return vgpuCount, nil
  1363. }
  1364. type PersistentVolumeClaimData struct {
  1365. Class string `json:"class"`
  1366. Claim string `json:"claim"`
  1367. Namespace string `json:"namespace"`
  1368. ClusterID string `json:"clusterId"`
  1369. TimesClaimed int `json:"timesClaimed"`
  1370. VolumeName string `json:"volumeName"`
  1371. Volume *costAnalyzerCloud.PV `json:"persistentVolume"`
  1372. Values []*util.Vector `json:"values"`
  1373. }
  1374. func measureTime(start time.Time, threshold time.Duration, name string) {
  1375. elapsed := time.Since(start)
  1376. if elapsed > threshold {
  1377. log.Infof("[Profiler] %s: %s", elapsed, name)
  1378. }
  1379. }
  1380. func (cm *CostModel) QueryAllocation(window opencost.Window, step time.Duration, aggregate []string, includeIdle, idleByNode, includeProportionalAssetResourceCosts, includeAggregatedMetadata, sharedLoadBalancer bool, accumulateBy opencost.AccumulateOption, shareIdle bool, filterString string) (*opencost.AllocationSetRange, error) {
  1381. // Validate window is legal
  1382. if window.IsOpen() || window.IsNegative() {
  1383. return nil, fmt.Errorf("illegal window: %s", window)
  1384. }
  1385. var totalsStore opencost.TotalsStore
  1386. // Idle is required for proportional asset costs
  1387. if includeProportionalAssetResourceCosts {
  1388. if !includeIdle {
  1389. return nil, errors.New("bad request - includeIdle must be set true if includeProportionalAssetResourceCosts is true")
  1390. }
  1391. totalsStore = opencost.NewMemoryTotalsStore()
  1392. }
  1393. // Begin with empty response
  1394. asr := opencost.NewAllocationSetRange()
  1395. // Query for AllocationSets in increments of the given step duration,
  1396. // appending each to the response.
  1397. stepStart := *window.Start()
  1398. stepEnd := stepStart.Add(step)
  1399. var isAKS bool
  1400. for window.End().After(stepStart) {
  1401. allocSet, err := cm.ComputeAllocation(stepStart, stepEnd)
  1402. if err != nil {
  1403. return nil, fmt.Errorf("error computing allocations for %s: %w", opencost.NewClosedWindow(stepStart, stepEnd), err)
  1404. }
  1405. if includeIdle {
  1406. assetSet, err := cm.ComputeAssets(stepStart, stepEnd)
  1407. if err != nil {
  1408. return nil, fmt.Errorf("error computing assets for %s: %w", opencost.NewClosedWindow(stepStart, stepEnd), err)
  1409. }
  1410. if includeProportionalAssetResourceCosts {
  1411. // AKS is a special case - there can be a maximum of 2
  1412. // load balancers (1 public and 1 private) in an AKS cluster
  1413. // therefore, when calculating PARCs for load balancers,
  1414. // we must know if this is an AKS cluster
  1415. for _, node := range assetSet.Nodes {
  1416. if _, found := node.Labels["label_kubernetes_azure_com_cluster"]; found {
  1417. isAKS = true
  1418. break
  1419. }
  1420. }
  1421. _, err := opencost.UpdateAssetTotalsStore(totalsStore, assetSet)
  1422. if err != nil {
  1423. log.Errorf("Allocation: error updating asset resource totals for %s: %s", assetSet.Window, err)
  1424. }
  1425. }
  1426. idleSet, err := computeIdleAllocations(allocSet, assetSet, idleByNode)
  1427. if err != nil {
  1428. return nil, fmt.Errorf("error computing idle allocations for %s: %w", opencost.NewClosedWindow(stepStart, stepEnd), err)
  1429. }
  1430. for _, idleAlloc := range idleSet.Allocations {
  1431. allocSet.Insert(idleAlloc)
  1432. }
  1433. }
  1434. asr.Append(allocSet)
  1435. stepStart = stepEnd
  1436. stepEnd = stepStart.Add(step)
  1437. }
  1438. // Apply allocation filter BEFORE aggregation if provided
  1439. if filterString != "" {
  1440. parser := allocation.NewAllocationFilterParser()
  1441. filterNode, err := parser.Parse(filterString)
  1442. if err != nil {
  1443. return nil, fmt.Errorf("invalid filter: %w", err)
  1444. }
  1445. compiler := opencost.NewAllocationMatchCompiler(nil)
  1446. matcher, err := compiler.Compile(filterNode)
  1447. if err != nil {
  1448. return nil, fmt.Errorf("failed to compile filter: %w", err)
  1449. }
  1450. filteredASR := opencost.NewAllocationSetRange()
  1451. for _, as := range asr.Slice() {
  1452. filteredAS := opencost.NewAllocationSet(as.Start(), as.End())
  1453. for _, alloc := range as.Allocations {
  1454. if matcher.Matches(alloc) {
  1455. filteredAS.Set(alloc)
  1456. }
  1457. }
  1458. if filteredAS.Length() > 0 {
  1459. filteredASR.Append(filteredAS)
  1460. }
  1461. }
  1462. asr = filteredASR
  1463. }
  1464. // Set aggregation options and aggregate
  1465. var shareIdleOpt string
  1466. if shareIdle {
  1467. shareIdleOpt = opencost.ShareWeighted
  1468. } else {
  1469. shareIdleOpt = opencost.ShareNone
  1470. }
  1471. opts := &opencost.AllocationAggregationOptions{
  1472. IncludeProportionalAssetResourceCosts: includeProportionalAssetResourceCosts,
  1473. IdleByNode: idleByNode,
  1474. IncludeAggregatedMetadata: includeAggregatedMetadata,
  1475. ShareIdle: shareIdleOpt,
  1476. }
  1477. // Aggregate
  1478. err := asr.AggregateBy(aggregate, opts)
  1479. if err != nil {
  1480. return nil, fmt.Errorf("error aggregating for %s: %w", window, err)
  1481. }
  1482. // Accumulate, if requested
  1483. if accumulateBy != opencost.AccumulateOptionNone {
  1484. asr, err = asr.Accumulate(accumulateBy)
  1485. if err != nil {
  1486. log.Errorf("error accumulating by %v: %s", accumulateBy, err)
  1487. return nil, fmt.Errorf("error accumulating by %v: %s", accumulateBy, err)
  1488. }
  1489. // when accumulating and returning PARCs, we need the totals for the
  1490. // accumulated windows to accurately compute a fraction
  1491. if includeProportionalAssetResourceCosts {
  1492. assetSet, err := cm.ComputeAssets(*asr.Window().Start(), *asr.Window().End())
  1493. if err != nil {
  1494. return nil, fmt.Errorf("error computing assets for %s: %w", opencost.NewClosedWindow(*asr.Window().Start(), *asr.Window().End()), err)
  1495. }
  1496. _, err = opencost.UpdateAssetTotalsStore(totalsStore, assetSet)
  1497. if err != nil {
  1498. log.Errorf("Allocation: error updating asset resource totals for %s: %s", opencost.NewClosedWindow(*asr.Window().Start(), *asr.Window().End()), err)
  1499. }
  1500. }
  1501. }
  1502. if includeProportionalAssetResourceCosts {
  1503. for _, as := range asr.Allocations {
  1504. totalStoreByNode, ok := totalsStore.GetAssetTotalsByNode(as.Start(), as.End())
  1505. if !ok {
  1506. log.Errorf("unable to locate allocation totals for node for window %v - %v", as.Start(), as.End())
  1507. return nil, fmt.Errorf("unable to locate allocation totals for node for window %v - %v", as.Start(), as.End())
  1508. }
  1509. totalStoreByCluster, ok := totalsStore.GetAssetTotalsByCluster(as.Start(), as.End())
  1510. if !ok {
  1511. log.Errorf("unable to locate allocation totals for cluster for window %v - %v", as.Start(), as.End())
  1512. return nil, fmt.Errorf("unable to locate allocation totals for cluster for window %v - %v", as.Start(), as.End())
  1513. }
  1514. var totalPublicLbCost, totalPrivateLbCost float64
  1515. if isAKS && sharedLoadBalancer {
  1516. // loop through all assetTotals, adding all load balancer costs by public and private
  1517. for _, tot := range totalStoreByNode {
  1518. if tot.PrivateLoadBalancer {
  1519. totalPrivateLbCost += tot.LoadBalancerCost
  1520. } else {
  1521. totalPublicLbCost += tot.LoadBalancerCost
  1522. }
  1523. }
  1524. }
  1525. // loop through each allocation set, using total cost from totals store
  1526. for _, alloc := range as.Allocations {
  1527. for rawKey, parc := range alloc.ProportionalAssetResourceCosts {
  1528. key := strings.TrimSuffix(strings.ReplaceAll(rawKey, ",", "/"), "/")
  1529. // for each parc , check the totals store for each
  1530. // on a totals hit, set the corresponding total and calculate percentage
  1531. var totals *opencost.AssetTotals
  1532. if totalsLoc, found := totalStoreByCluster[key]; found {
  1533. totals = totalsLoc
  1534. }
  1535. if totalsLoc, found := totalStoreByNode[key]; found {
  1536. totals = totalsLoc
  1537. }
  1538. if totals == nil {
  1539. log.Errorf("unable to locate asset totals for allocation %s, corresponding PARC is being skipped", key)
  1540. continue
  1541. }
  1542. parc.CPUTotalCost = totals.CPUCost
  1543. parc.GPUTotalCost = totals.GPUCost
  1544. parc.RAMTotalCost = totals.RAMCost
  1545. parc.PVTotalCost = totals.PersistentVolumeCost
  1546. if isAKS && sharedLoadBalancer && len(alloc.LoadBalancers) > 0 {
  1547. // Azure is a special case - use computed totals above
  1548. // use the lbAllocations in the object to determine if
  1549. // this PARC is a public or private load balancer
  1550. // then set the total accordingly
  1551. // AKS only has 1 public and 1 private load balancer
  1552. lbAlloc, found := alloc.LoadBalancers[key]
  1553. if found {
  1554. if lbAlloc.Private {
  1555. parc.LoadBalancerTotalCost = totalPrivateLbCost
  1556. } else {
  1557. parc.LoadBalancerTotalCost = totalPublicLbCost
  1558. }
  1559. }
  1560. } else {
  1561. parc.LoadBalancerTotalCost = totals.LoadBalancerCost
  1562. }
  1563. opencost.ComputePercentages(&parc)
  1564. alloc.ProportionalAssetResourceCosts[rawKey] = parc
  1565. }
  1566. }
  1567. }
  1568. }
  1569. return asr, nil
  1570. }
  1571. // debugAssetAllocationMismatch analyzes and logs discrepancies between asset and allocation data
  1572. // This helps diagnose pricing issues and negative idle costs
  1573. func debugAssetAllocationMismatch(allocSet *opencost.AllocationSet, assetSet *opencost.AssetSet) {
  1574. log.Debugf("=== Asset-Allocation Debug Analysis for window %s ===", allocSet.Window)
  1575. // Build maps for efficient lookup
  1576. assetsByProviderID := make(map[string]*opencost.Node)
  1577. assetsByNode := make(map[string]*opencost.Node)
  1578. for _, asset := range assetSet.Nodes {
  1579. if asset.Properties != nil && asset.Properties.ProviderID != "" {
  1580. assetsByProviderID[asset.Properties.ProviderID] = asset
  1581. }
  1582. if asset.Properties != nil && asset.Properties.Name != "" {
  1583. assetsByNode[asset.Properties.Name] = asset
  1584. }
  1585. }
  1586. // 1) Find allocations without matching assets (by ProviderID)
  1587. allocsWithoutAssets := make([]*opencost.Allocation, 0)
  1588. for _, alloc := range allocSet.Allocations {
  1589. if alloc.Properties == nil {
  1590. continue
  1591. }
  1592. providerID := alloc.Properties.ProviderID
  1593. if providerID == "" {
  1594. continue
  1595. }
  1596. if _, found := assetsByProviderID[providerID]; !found {
  1597. allocsWithoutAssets = append(allocsWithoutAssets, alloc)
  1598. }
  1599. }
  1600. if len(allocsWithoutAssets) > 0 {
  1601. log.Debugf("Found %d allocations without matching assets:", len(allocsWithoutAssets))
  1602. for _, alloc := range allocsWithoutAssets {
  1603. log.Debugf(" - Allocation: %s, Node: %s, ProviderID: %s, TotalCost: %.4f",
  1604. alloc.Name,
  1605. alloc.Properties.Node,
  1606. alloc.Properties.ProviderID,
  1607. alloc.TotalCost())
  1608. }
  1609. }
  1610. // 2) Sum allocations per node and compare to node asset costs
  1611. allocTotalsByNode := make(map[string]*struct {
  1612. CPUCost float64
  1613. GPUCost float64
  1614. RAMCost float64
  1615. TotalCost float64
  1616. CPUCoreHours float64
  1617. GPUHours float64
  1618. RAMByteHours float64
  1619. Count int
  1620. })
  1621. for _, alloc := range allocSet.Allocations {
  1622. if alloc.Properties == nil || alloc.Properties.Node == "" {
  1623. continue
  1624. }
  1625. node := alloc.Properties.Node
  1626. if _, exists := allocTotalsByNode[node]; !exists {
  1627. allocTotalsByNode[node] = &struct {
  1628. CPUCost float64
  1629. GPUCost float64
  1630. RAMCost float64
  1631. TotalCost float64
  1632. CPUCoreHours float64
  1633. GPUHours float64
  1634. RAMByteHours float64
  1635. Count int
  1636. }{}
  1637. }
  1638. allocTotalsByNode[node].CPUCost += alloc.CPUCost
  1639. allocTotalsByNode[node].GPUCost += alloc.GPUCost
  1640. allocTotalsByNode[node].RAMCost += alloc.RAMCost
  1641. allocTotalsByNode[node].TotalCost += alloc.TotalCost()
  1642. allocTotalsByNode[node].CPUCoreHours += alloc.CPUCoreHours
  1643. allocTotalsByNode[node].GPUHours += alloc.GPUHours
  1644. allocTotalsByNode[node].RAMByteHours += alloc.RAMByteHours
  1645. allocTotalsByNode[node].Count++
  1646. }
  1647. log.Debugf("Per-Node Asset vs Allocation Comparison:")
  1648. for node, allocTotals := range allocTotalsByNode {
  1649. asset, hasAsset := assetsByNode[node]
  1650. if !hasAsset {
  1651. log.Debugf(" Node %s: Has allocations but NO ASSET (allocations: %d, total cost: %.4f)",
  1652. node, allocTotals.Count, allocTotals.TotalCost)
  1653. continue
  1654. }
  1655. assetCPU := asset.CPUCost
  1656. assetGPU := asset.GPUCost
  1657. assetRAM := asset.RAMCost
  1658. assetTotal := asset.TotalCost()
  1659. cpuDiff := assetCPU - allocTotals.CPUCost
  1660. gpuDiff := assetGPU - allocTotals.GPUCost
  1661. ramDiff := assetRAM - allocTotals.RAMCost
  1662. totalDiff := assetTotal - allocTotals.TotalCost
  1663. status := "OK"
  1664. if cpuDiff < 0 || gpuDiff < 0 || ramDiff < 0 {
  1665. status = "NEGATIVE_IDLE"
  1666. }
  1667. log.Debugf(" Node %s [%s]:", node, status)
  1668. log.Debugf(" Asset: CPU=%.4f, GPU=%.4f, RAM=%.4f, Total=%.4f",
  1669. assetCPU, assetGPU, assetRAM, assetTotal)
  1670. log.Debugf(" Allocation: CPU=%.4f, GPU=%.4f, RAM=%.4f, Total=%.4f (%d allocs)",
  1671. allocTotals.CPUCost, allocTotals.GPUCost, allocTotals.RAMCost, allocTotals.TotalCost, allocTotals.Count)
  1672. log.Debugf(" Difference: CPU=%.4f, GPU=%.4f, RAM=%.4f, Total=%.4f",
  1673. cpuDiff, gpuDiff, ramDiff, totalDiff)
  1674. if asset.Adjustment != 0 {
  1675. log.Debugf(" Adjustment: %.4f", asset.Adjustment)
  1676. }
  1677. // Compare resource amounts vs costs: higher resources should have higher costs
  1678. assetCPUHours := asset.CPUCoreHours
  1679. assetGPUHours := asset.GPUHours
  1680. assetRAMBytes := asset.RAMByteHours
  1681. allocCPUHours := allocTotals.CPUCoreHours
  1682. allocGPUHours := allocTotals.GPUHours
  1683. allocRAMBytes := allocTotals.RAMByteHours
  1684. // Warn if resource amounts and costs are inverted (higher resources but lower costs)
  1685. if assetCPUHours > 0 && allocCPUHours > 0 {
  1686. if assetCPUHours > allocCPUHours && assetCPU < allocTotals.CPUCost {
  1687. log.Warnf("Resource-cost inversion for %s CPU: asset has MORE hours (%.2f) but LESS cost (%.4f) than allocations (hours: %.2f, cost: %.4f)",
  1688. node, assetCPUHours, assetCPU, allocCPUHours, allocTotals.CPUCost)
  1689. } else if assetCPUHours < allocCPUHours && assetCPU > allocTotals.CPUCost {
  1690. log.Warnf("Resource-cost inversion for %s CPU: asset has LESS hours (%.2f) but MORE cost (%.4f) than allocations (hours: %.2f, cost: %.4f)",
  1691. node, assetCPUHours, assetCPU, allocCPUHours, allocTotals.CPUCost)
  1692. }
  1693. }
  1694. if assetGPUHours > 0 && allocGPUHours > 0 {
  1695. if assetGPUHours > allocGPUHours && assetGPU < allocTotals.GPUCost {
  1696. log.Warnf("Resource-cost inversion for %s GPU: asset has MORE hours (%.2f) but LESS cost (%.4f) than allocations (hours: %.2f, cost: %.4f)",
  1697. node, assetGPUHours, assetGPU, allocGPUHours, allocTotals.GPUCost)
  1698. } else if assetGPUHours < allocGPUHours && assetGPU > allocTotals.GPUCost {
  1699. log.Warnf("Resource-cost inversion for %s GPU: asset has LESS hours (%.2f) but MORE cost (%.4f) than allocations (hours: %.2f, cost: %.4f)",
  1700. node, assetGPUHours, assetGPU, allocGPUHours, allocTotals.GPUCost)
  1701. }
  1702. }
  1703. if assetRAMBytes > 0 && allocRAMBytes > 0 {
  1704. if assetRAMBytes > allocRAMBytes && assetRAM < allocTotals.RAMCost {
  1705. log.Warnf("Resource-cost inversion for %s RAM: asset has MORE byte-hours (%.2f) but LESS cost (%.4f) than allocations (byte-hours: %.2f, cost: %.4f)",
  1706. node, assetRAMBytes, assetRAM, allocRAMBytes, allocTotals.RAMCost)
  1707. } else if assetRAMBytes < allocRAMBytes && assetRAM > allocTotals.RAMCost {
  1708. log.Warnf("Resource-cost inversion for %s RAM: asset has LESS byte-hours (%.2f) but MORE cost (%.4f) than allocations (byte-hours: %.2f, cost: %.4f)",
  1709. node, assetRAMBytes, assetRAM, allocRAMBytes, allocTotals.RAMCost)
  1710. }
  1711. }
  1712. // Log resource amounts for debugging
  1713. log.Debugf(" Resource Hours:")
  1714. log.Debugf(" Asset: CPU=%.2f hours, GPU=%.2f hours, RAM=%.2f byte-hours",
  1715. assetCPUHours, assetGPUHours, assetRAMBytes)
  1716. log.Debugf(" Allocation: CPU=%.2f hours, GPU=%.2f hours, RAM=%.2f byte-hours",
  1717. allocCPUHours, allocGPUHours, allocRAMBytes)
  1718. }
  1719. // 3) Sum total of all node costs
  1720. totalNodeCPU := 0.0
  1721. totalNodeGPU := 0.0
  1722. totalNodeRAM := 0.0
  1723. totalNodeCost := 0.0
  1724. nodeCount := 0
  1725. for _, asset := range assetSet.Nodes {
  1726. totalNodeCPU += asset.CPUCost
  1727. totalNodeGPU += asset.GPUCost
  1728. totalNodeRAM += asset.RAMCost
  1729. totalNodeCost += asset.TotalCost()
  1730. nodeCount++
  1731. }
  1732. log.Debugf("Total Node Asset Costs:")
  1733. log.Debugf(" Nodes: %d", nodeCount)
  1734. log.Debugf(" CPU: %.4f", totalNodeCPU)
  1735. log.Debugf(" GPU: %.4f", totalNodeGPU)
  1736. log.Debugf(" RAM: %.4f", totalNodeRAM)
  1737. log.Debugf(" Total: %.4f", totalNodeCost)
  1738. // 4) Sum total of all allocation costs
  1739. totalAllocCPU := 0.0
  1740. totalAllocGPU := 0.0
  1741. totalAllocRAM := 0.0
  1742. totalAllocCost := 0.0
  1743. allocCount := 0
  1744. for _, alloc := range allocSet.Allocations {
  1745. totalAllocCPU += alloc.CPUCost
  1746. totalAllocGPU += alloc.GPUCost
  1747. totalAllocRAM += alloc.RAMCost
  1748. totalAllocCost += alloc.TotalCost()
  1749. allocCount++
  1750. }
  1751. log.Debugf("Total Allocation Costs:")
  1752. log.Debugf(" Allocations: %d", allocCount)
  1753. log.Debugf(" CPU: %.4f", totalAllocCPU)
  1754. log.Debugf(" GPU: %.4f", totalAllocGPU)
  1755. log.Debugf(" RAM: %.4f", totalAllocRAM)
  1756. log.Debugf(" Total: %.4f", totalAllocCost)
  1757. // Overall comparison
  1758. log.Debugf("Overall Asset vs Allocation:")
  1759. log.Debugf(" CPU Difference: %.4f (Asset - Allocation)", totalNodeCPU-totalAllocCPU)
  1760. log.Debugf(" GPU Difference: %.4f (Asset - Allocation)", totalNodeGPU-totalAllocGPU)
  1761. log.Debugf(" RAM Difference: %.4f (Asset - Allocation)", totalNodeRAM-totalAllocRAM)
  1762. log.Debugf(" Total Difference: %.4f (Asset - Allocation)", totalNodeCost-totalAllocCost)
  1763. log.Debugf("=== End Asset-Allocation Debug Analysis ===")
  1764. }
  1765. func computeIdleAllocations(allocSet *opencost.AllocationSet, assetSet *opencost.AssetSet, idleByNode bool) (*opencost.AllocationSet, error) {
  1766. if !allocSet.Window.Equal(assetSet.Window) {
  1767. return nil, fmt.Errorf("cannot compute idle allocations for mismatched sets: %s does not equal %s", allocSet.Window, assetSet.Window)
  1768. }
  1769. // Run debug analysis when log level is debug
  1770. debugAssetAllocationMismatch(allocSet, assetSet)
  1771. var allocTotals map[string]*opencost.AllocationTotals
  1772. var assetTotals map[string]*opencost.AssetTotals
  1773. if idleByNode {
  1774. allocTotals = opencost.ComputeAllocationTotals(allocSet, opencost.AllocationNodeProp)
  1775. assetTotals = opencost.ComputeAssetTotals(assetSet, true)
  1776. } else {
  1777. allocTotals = opencost.ComputeAllocationTotals(allocSet, opencost.AllocationClusterProp)
  1778. assetTotals = opencost.ComputeAssetTotals(assetSet, false)
  1779. }
  1780. start, end := *allocSet.Window.Start(), *allocSet.Window.End()
  1781. idleSet := opencost.NewAllocationSet(start, end)
  1782. for key, assetTotal := range assetTotals {
  1783. allocTotal, ok := allocTotals[key]
  1784. if !ok {
  1785. log.Warnf("Allocation: did not find allocations for asset key: %s", key)
  1786. // Use a zero-value set of totals. This indicates either (1) an
  1787. // error computing totals, or (2) that no allocations ran on the
  1788. // given node for the given window.
  1789. allocTotal = &opencost.AllocationTotals{
  1790. Cluster: assetTotal.Cluster,
  1791. Node: assetTotal.Node,
  1792. Start: assetTotal.Start,
  1793. End: assetTotal.End,
  1794. }
  1795. }
  1796. // Insert one idle allocation for each key (whether by node or
  1797. // by cluster), defined as the difference between the total
  1798. // asset cost and the allocated cost per-resource.
  1799. // Idle costs are clamped to zero to prevent negative values that can occur
  1800. // when asset total costs are less than allocated costs. This can happen when:
  1801. // - Pricing data is unavailable (promless mode, API failures, missing price data)
  1802. // - Custom pricing is misconfigured or returns zero values
  1803. // - Cloud billing adjustments reduce asset costs below allocation costs
  1804. // - Allocation calculations exceed asset costs due to timing or rounding
  1805. name := fmt.Sprintf("%s/%s", key, opencost.IdleSuffix)
  1806. cpuIdleCost := assetTotal.TotalCPUCost() - allocTotal.TotalCPUCost()
  1807. gpuIdleCost := assetTotal.TotalGPUCost() - allocTotal.TotalGPUCost()
  1808. ramIdleCost := assetTotal.TotalRAMCost() - allocTotal.TotalRAMCost()
  1809. // Clamp idle costs to zero to prevent negative idle allocations
  1810. if cpuIdleCost < 0 {
  1811. log.Warnf("Negative CPU idle cost detected for %s: asset total (%.4f) < allocation total (%.4f), clamping to 0",
  1812. key, assetTotal.TotalCPUCost(), allocTotal.TotalCPUCost())
  1813. cpuIdleCost = 0
  1814. }
  1815. if gpuIdleCost < 0 {
  1816. log.Warnf("Negative GPU idle cost detected for %s: asset total (%.4f) < allocation total (%.4f), clamping to 0",
  1817. key, assetTotal.TotalGPUCost(), allocTotal.TotalGPUCost())
  1818. gpuIdleCost = 0
  1819. }
  1820. if ramIdleCost < 0 {
  1821. log.Warnf("Negative RAM idle cost detected for %s: asset total (%.4f) < allocation total (%.4f), clamping to 0",
  1822. key, assetTotal.TotalRAMCost(), allocTotal.TotalRAMCost())
  1823. ramIdleCost = 0
  1824. }
  1825. err := idleSet.Insert(&opencost.Allocation{
  1826. Name: name,
  1827. Window: idleSet.Window.Clone(),
  1828. Properties: &opencost.AllocationProperties{
  1829. Cluster: assetTotal.Cluster,
  1830. Node: assetTotal.Node,
  1831. ProviderID: assetTotal.ProviderID,
  1832. },
  1833. Start: assetTotal.Start,
  1834. End: assetTotal.End,
  1835. CPUCost: cpuIdleCost,
  1836. GPUCost: gpuIdleCost,
  1837. RAMCost: ramIdleCost,
  1838. })
  1839. if err != nil {
  1840. return nil, fmt.Errorf("failed to insert idle allocation %s: %w", name, err)
  1841. }
  1842. }
  1843. return idleSet, nil
  1844. }
  1845. func (cm *CostModel) GetDataSource() source.OpenCostDataSource {
  1846. return cm.DataSource
  1847. }