costmodel.go 69 KB

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