allocation_helpers.go 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614
  1. package costmodel
  2. import (
  3. "fmt"
  4. "math"
  5. "strconv"
  6. "strings"
  7. "time"
  8. coreenv "github.com/opencost/opencost/core/pkg/env"
  9. "github.com/opencost/opencost/core/pkg/log"
  10. "github.com/opencost/opencost/core/pkg/opencost"
  11. "github.com/opencost/opencost/core/pkg/source"
  12. "github.com/opencost/opencost/core/pkg/util"
  13. "github.com/opencost/opencost/pkg/cloud/provider"
  14. "k8s.io/apimachinery/pkg/labels"
  15. )
  16. // This is a bit of a hack to work around garbage data from cadvisor
  17. // Ideally you cap each pod to the max CPU on its node, but that involves a bit more complexity, as it it would need to be done when allocations joins with asset data.
  18. const CPU_SANITY_LIMIT = 512
  19. // Sanity Limit for PV usage, set to 10 PB, in bytes for now
  20. const KiB = 1024.0
  21. const MiB = 1024.0 * KiB
  22. const GiB = 1024.0 * MiB
  23. const TiB = 1024.0 * GiB
  24. const PiB = 1024.0 * TiB
  25. const PV_USAGE_SANITY_LIMIT_BYTES = 10.0 * PiB
  26. const (
  27. GpuUsageAverageMode = "AVERAGE"
  28. GpuUsageMaxMode = "MAX"
  29. GpuIsSharedMode = "SHARED"
  30. GpuInfoMode = "GPU_INFO"
  31. )
  32. /* Pod Helpers */
  33. func (cm *CostModel) buildPodMap(window opencost.Window, podMap map[podKey]*pod, ingestPodUID bool, podUIDKeyMap map[podKey][]podKey) error {
  34. // Assumes that window is positive and closed
  35. start, end := *window.Start(), *window.End()
  36. grp := source.NewQueryGroup()
  37. ds := cm.DataSource.Metrics()
  38. resolution := cm.DataSource.Resolution()
  39. var resPods []*source.PodsResult
  40. var err error
  41. maxTries := 3
  42. numTries := 0
  43. for resPods == nil && numTries < maxTries {
  44. numTries++
  45. // Submit and profile query
  46. var queryPodsResult *source.QueryGroupFuture[source.PodsResult]
  47. if ingestPodUID {
  48. queryPodsResult = source.WithGroup(grp, ds.QueryPodsUID(start, end))
  49. } else {
  50. queryPodsResult = source.WithGroup(grp, ds.QueryPods(start, end))
  51. }
  52. queryProfile := time.Now()
  53. resPods, err = queryPodsResult.Await()
  54. if err != nil {
  55. log.Profile(queryProfile, fmt.Sprintf("CostModel.ComputeAllocation: pod query try %d failed: %s", numTries, err))
  56. resPods = nil
  57. }
  58. }
  59. if err != nil {
  60. return err
  61. }
  62. // When ingesting UID, fill in missing UIDs from kube_pod_labels as a fallback (e.g. when
  63. // kube_pod_container_status_running comes from a scrape job that doesn't expose uid).
  64. if ingestPodUID {
  65. uidFromLabels := cm.buildPodUIDFromLabelsMap(start, end)
  66. for _, res := range resPods {
  67. if res.UID != "" {
  68. continue
  69. }
  70. cluster := res.Cluster
  71. if cluster == "" {
  72. cluster = coreenv.GetClusterID()
  73. }
  74. key := podUIDLookupKey(cluster, res.Namespace, res.Pod)
  75. if uid, ok := uidFromLabels[key]; ok {
  76. res.UID = uid
  77. }
  78. }
  79. }
  80. // queryFmtPodsUID will return both UID-containing results, and non-UID-containing results,
  81. // so filter so we don't duplicate pods: keep all with UID; keep those without UID only when
  82. // no other result for the same (cluster, namespace, pod) has a UID.
  83. if ingestPodUID {
  84. resPods = filterPodsByUIDWithDedup(resPods)
  85. if len(resPods) == 0 {
  86. log.DedupedWarningf(5, "CostModel.ComputeAllocation: UID ingestion enabled, but query did not return any results with UID")
  87. }
  88. }
  89. applyPodResults(window, resolution, podMap, resPods, ingestPodUID, podUIDKeyMap)
  90. rebuildPodUIDKeyMapFromPodMap(podMap, podUIDKeyMap, ingestPodUID)
  91. return nil
  92. }
  93. // podUIDLookupKey returns a map key for (cluster, namespace, pod). Used for UID fallback lookup.
  94. func podUIDLookupKey(cluster, namespace, pod string) string {
  95. return cluster + "|" + namespace + "|" + pod
  96. }
  97. // buildPodUIDFromLabelsMap queries kube_pod_labels and returns a map of (cluster|namespace|pod) -> uid
  98. func (cm *CostModel) buildPodUIDFromLabelsMap(start, end time.Time) map[string]string {
  99. ds := cm.DataSource.Metrics()
  100. res, err := ds.QueryPodLabels(start, end).Await()
  101. if err != nil {
  102. log.DedupedWarningf(5, "CostModel.ComputeAllocation: pod labels query failed, skipping UID fallback: %s", err)
  103. return nil
  104. }
  105. m := make(map[string]string)
  106. for _, r := range res {
  107. if r.UID == "" {
  108. continue
  109. }
  110. cluster := r.Cluster
  111. if cluster == "" {
  112. cluster = coreenv.GetClusterID()
  113. }
  114. m[podUIDLookupKey(cluster, r.Namespace, r.Pod)] = r.UID
  115. }
  116. return m
  117. }
  118. // filterPodsByUIDWithDedup returns exactly one PodsResult per (cluster, namespace, pod) to prevent
  119. // duplicate pod results. Prefers a result with non-empty UID when the same pod appears with and
  120. // without UID or from multiple scrape jobs.
  121. func filterPodsByUIDWithDedup(resPods []*source.PodsResult) []*source.PodsResult {
  122. // key -> chosen result (we keep exactly one per key)
  123. byKey := make(map[string]*source.PodsResult)
  124. for _, res := range resPods {
  125. cluster := res.Cluster
  126. if cluster == "" {
  127. cluster = coreenv.GetClusterID()
  128. }
  129. key := podUIDLookupKey(cluster, res.Namespace, res.Pod)
  130. existing, ok := byKey[key]
  131. if !ok {
  132. byKey[key] = res
  133. continue
  134. }
  135. if res.UID != "" && existing.UID == "" {
  136. byKey[key] = res
  137. }
  138. }
  139. out := make([]*source.PodsResult, 0, len(byKey))
  140. for _, res := range byKey {
  141. out = append(out, res)
  142. }
  143. return out
  144. }
  145. // nameOnlyFromPodKey returns the name-only key (cluster, namespace, pod name without UID suffix)
  146. func nameOnlyFromPodKey(key podKey, ingestPodUID bool) podKey {
  147. if !ingestPodUID {
  148. return key
  149. }
  150. idx := strings.LastIndex(key.Pod, " ")
  151. if idx <= 0 {
  152. return key
  153. }
  154. return newPodKey(key.Cluster, key.Namespace, key.Pod[:idx])
  155. }
  156. // rebuildPodUIDKeyMapFromPodMap repopulates podUIDKeyMap from the current podMap
  157. func rebuildPodUIDKeyMapFromPodMap(podMap map[podKey]*pod, podUIDKeyMap map[podKey][]podKey, ingestPodUID bool) {
  158. for k := range podUIDKeyMap {
  159. delete(podUIDKeyMap, k)
  160. }
  161. defaultCluster := coreenv.GetClusterID()
  162. for key := range podMap {
  163. nameOnly := nameOnlyFromPodKey(key, ingestPodUID)
  164. podUIDKeyMap[nameOnly] = append(podUIDKeyMap[nameOnly], key)
  165. if nameOnly.Cluster != defaultCluster {
  166. alt := newPodKey(defaultCluster, nameOnly.Namespace, nameOnly.Pod)
  167. podUIDKeyMap[alt] = append(podUIDKeyMap[alt], key)
  168. }
  169. }
  170. }
  171. func applyPodResults(window opencost.Window, resolution time.Duration, podMap map[podKey]*pod, resPods []*source.PodsResult, ingestPodUID bool, podUIDKeyMap map[podKey][]podKey) {
  172. for _, res := range resPods {
  173. if len(res.Data) == 0 {
  174. log.Warnf("CostModel.ComputeAllocation: empty minutes result")
  175. continue
  176. }
  177. cluster := res.Cluster
  178. if cluster == "" {
  179. cluster = coreenv.GetClusterID()
  180. }
  181. namespace := res.Namespace
  182. if namespace == "" {
  183. log.Warnf("CostModel.ComputeAllocation: minutes query result missing field: namespace")
  184. continue
  185. }
  186. podName := res.Pod
  187. if podName == "" {
  188. log.Warnf("CostModel.ComputeAllocation: minutes query result missing field: pod")
  189. continue
  190. }
  191. key := newPodKey(cluster, namespace, podName)
  192. // If ingesting UID, key pods by "name uid" so we can distinguish restarts
  193. if ingestPodUID && res.UID != "" {
  194. key = newPodKey(cluster, namespace, podName+" "+res.UID)
  195. } else if ingestPodUID && res.UID == "" {
  196. log.Warnf("CostModel.ComputeAllocation: UID ingestion enabled, but query result missing field: uid")
  197. }
  198. allocStart, allocEnd := calculateStartAndEnd(res.Data, resolution, window)
  199. if allocStart.IsZero() || allocEnd.IsZero() {
  200. continue
  201. }
  202. if thisPod, ok := podMap[key]; ok {
  203. // Pod has already been recorded, so update it accordingly
  204. if allocStart.Before(thisPod.Start) {
  205. thisPod.Start = allocStart
  206. }
  207. if allocEnd.After(thisPod.End) {
  208. thisPod.End = allocEnd
  209. }
  210. } else {
  211. // pod has not been recorded yet, so insert it
  212. podMap[key] = &pod{
  213. Window: window.Clone(),
  214. Start: allocStart,
  215. End: allocEnd,
  216. Key: key,
  217. Allocations: map[string]*opencost.Allocation{},
  218. }
  219. }
  220. }
  221. }
  222. func applyCPUCoresAllocated(podMap map[podKey]*pod, resCPUCoresAllocated []*source.CPUCoresAllocatedResult, podUIDKeyMap map[podKey][]podKey) {
  223. for _, res := range resCPUCoresAllocated {
  224. key, err := newResultPodKey(res.Cluster, res.Namespace, res.Pod)
  225. if err != nil {
  226. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU allocation result missing field: %s", err)
  227. continue
  228. }
  229. container := res.Container
  230. if container == "" {
  231. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU allocation query result missing 'container': %s", key)
  232. continue
  233. }
  234. var pods []*pod
  235. if thisPod, ok := podMap[key]; !ok {
  236. if uidKeys, ok := podUIDKeyMap[key]; ok {
  237. for _, uidKey := range uidKeys {
  238. thisPod, ok = podMap[uidKey]
  239. if ok {
  240. pods = append(pods, thisPod)
  241. }
  242. }
  243. } else {
  244. continue
  245. }
  246. } else {
  247. pods = []*pod{thisPod}
  248. }
  249. for _, thisPod := range pods {
  250. if _, ok := thisPod.Allocations[container]; !ok {
  251. thisPod.appendContainer(container)
  252. }
  253. cpuCores := res.Data[0].Value
  254. if cpuCores > CPU_SANITY_LIMIT {
  255. log.Infof("[WARNING] Very large cpu allocation, clamping to %f", res.Data[0].Value*(thisPod.Allocations[container].Minutes()/60.0))
  256. cpuCores = 0.0
  257. }
  258. hours := thisPod.Allocations[container].Minutes() / 60.0
  259. thisPod.Allocations[container].CPUCoreHours = cpuCores * hours
  260. node := res.Node
  261. if node == "" {
  262. log.Warnf("CostModel.ComputeAllocation: CPU allocation query result missing 'node': %s", key)
  263. continue
  264. }
  265. thisPod.Allocations[container].Properties.Node = node
  266. thisPod.Node = node
  267. }
  268. }
  269. }
  270. func applyCPUCoresRequested(podMap map[podKey]*pod, resCPUCoresRequested []*source.CPURequestsResult, podUIDKeyMap map[podKey][]podKey) {
  271. for _, res := range resCPUCoresRequested {
  272. key, err := newResultPodKey(res.Cluster, res.Namespace, res.Pod)
  273. if err != nil {
  274. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU request result missing field: %s", err)
  275. continue
  276. }
  277. container := res.Container
  278. if container == "" {
  279. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU request query result missing 'container': %s", key)
  280. continue
  281. }
  282. var pods []*pod
  283. if thisPod, ok := podMap[key]; !ok {
  284. if uidKeys, ok := podUIDKeyMap[key]; ok {
  285. for _, uidKey := range uidKeys {
  286. thisPod, ok = podMap[uidKey]
  287. if ok {
  288. pods = append(pods, thisPod)
  289. }
  290. }
  291. } else {
  292. continue
  293. }
  294. } else {
  295. pods = []*pod{thisPod}
  296. }
  297. for _, thisPod := range pods {
  298. if _, ok := thisPod.Allocations[container]; !ok {
  299. thisPod.appendContainer(container)
  300. }
  301. thisPod.Allocations[container].CPUCoreRequestAverage = res.Data[0].Value
  302. // If CPU allocation is less than requests, set CPUCoreHours to
  303. // request level.
  304. if thisPod.Allocations[container].CPUCores() < res.Data[0].Value {
  305. thisPod.Allocations[container].CPUCoreHours = res.Data[0].Value * (thisPod.Allocations[container].Minutes() / 60.0)
  306. }
  307. if thisPod.Allocations[container].CPUCores() > CPU_SANITY_LIMIT {
  308. log.Infof("[WARNING] Very large cpu allocation, clamping! to %f", res.Data[0].Value*(thisPod.Allocations[container].Minutes()/60.0))
  309. thisPod.Allocations[container].CPUCoreHours = res.Data[0].Value * (thisPod.Allocations[container].Minutes() / 60.0)
  310. }
  311. node := res.Node
  312. if node == "" {
  313. log.Warnf("CostModel.ComputeAllocation: CPU request query result missing 'node': %s", key)
  314. continue
  315. }
  316. thisPod.Allocations[container].Properties.Node = node
  317. thisPod.Node = node
  318. }
  319. }
  320. }
  321. func applyCPUCoresLimits(podMap map[podKey]*pod, resCPUCoresLimits []*source.CPULimitsResult, podUIDKeyMap map[podKey][]podKey) {
  322. for _, res := range resCPUCoresLimits {
  323. key, err := newResultPodKey(res.Cluster, res.Namespace, res.Pod)
  324. if err != nil {
  325. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU limit result missing field: %s", err)
  326. continue
  327. }
  328. container := res.Container
  329. if container == "" {
  330. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU limit query result missing 'container': %s", key)
  331. continue
  332. }
  333. var pods []*pod
  334. if thisPod, ok := podMap[key]; !ok {
  335. if uidKeys, ok := podUIDKeyMap[key]; ok {
  336. for _, uidKey := range uidKeys {
  337. thisPod, ok = podMap[uidKey]
  338. if ok {
  339. pods = append(pods, thisPod)
  340. }
  341. }
  342. } else {
  343. continue
  344. }
  345. } else {
  346. pods = []*pod{thisPod}
  347. }
  348. for _, thisPod := range pods {
  349. if _, ok := thisPod.Allocations[container]; !ok {
  350. thisPod.appendContainer(container)
  351. }
  352. thisPod.Allocations[container].CPUCoreLimitAverage = res.Data[0].Value
  353. }
  354. }
  355. }
  356. func applyCPUCoresUsedAvg(podMap map[podKey]*pod, resCPUCoresUsedAvg []*source.CPUUsageAvgResult, podUIDKeyMap map[podKey][]podKey) {
  357. for _, res := range resCPUCoresUsedAvg {
  358. key, err := newResultPodKey(res.Cluster, res.Namespace, res.Pod)
  359. if err != nil {
  360. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU usage avg result missing field: %s", err)
  361. continue
  362. }
  363. container := res.Container
  364. if container == "" {
  365. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU usage avg query result missing 'container': %s", key)
  366. continue
  367. }
  368. var pods []*pod
  369. if thisPod, ok := podMap[key]; !ok {
  370. if uidKeys, ok := podUIDKeyMap[key]; ok {
  371. for _, uidKey := range uidKeys {
  372. thisPod, ok = podMap[uidKey]
  373. if ok {
  374. pods = append(pods, thisPod)
  375. }
  376. }
  377. } else {
  378. continue
  379. }
  380. } else {
  381. pods = []*pod{thisPod}
  382. }
  383. for _, thisPod := range pods {
  384. if _, ok := thisPod.Allocations[container]; !ok {
  385. thisPod.appendContainer(container)
  386. }
  387. thisPod.Allocations[container].CPUCoreUsageAverage = res.Data[0].Value
  388. if res.Data[0].Value > CPU_SANITY_LIMIT {
  389. log.Infof("[WARNING] Very large cpu USAGE, dropping outlier")
  390. thisPod.Allocations[container].CPUCoreUsageAverage = 0.0
  391. }
  392. }
  393. }
  394. }
  395. func applyCPUCoresUsedMax(podMap map[podKey]*pod, resCPUCoresUsedMax []*source.CPUUsageMaxResult, podUIDKeyMap map[podKey][]podKey) {
  396. for _, res := range resCPUCoresUsedMax {
  397. key, err := newResultPodKey(res.Cluster, res.Namespace, res.Pod)
  398. if err != nil {
  399. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU usage max result missing field: %s", err)
  400. continue
  401. }
  402. container := res.Container
  403. if container == "" {
  404. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU usage max query result missing 'container': %s", key)
  405. continue
  406. }
  407. var pods []*pod
  408. if thisPod, ok := podMap[key]; !ok {
  409. if uidKeys, ok := podUIDKeyMap[key]; ok {
  410. for _, uidKey := range uidKeys {
  411. thisPod, ok = podMap[uidKey]
  412. if ok {
  413. pods = append(pods, thisPod)
  414. }
  415. }
  416. } else {
  417. continue
  418. }
  419. } else {
  420. pods = []*pod{thisPod}
  421. }
  422. for _, thisPod := range pods {
  423. if _, ok := thisPod.Allocations[container]; !ok {
  424. thisPod.appendContainer(container)
  425. }
  426. if thisPod.Allocations[container].RawAllocationOnly == nil {
  427. thisPod.Allocations[container].RawAllocationOnly = &opencost.RawAllocationOnlyData{
  428. CPUCoreUsageMax: res.Data[0].Value,
  429. }
  430. } else {
  431. thisPod.Allocations[container].RawAllocationOnly.CPUCoreUsageMax = res.Data[0].Value
  432. }
  433. }
  434. }
  435. }
  436. func applyRAMBytesAllocated(podMap map[podKey]*pod, resRAMBytesAllocated []*source.RAMBytesAllocatedResult, podUIDKeyMap map[podKey][]podKey) {
  437. for _, res := range resRAMBytesAllocated {
  438. key, err := newResultPodKey(res.Cluster, res.Namespace, res.Pod)
  439. if err != nil {
  440. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM allocation result missing field: %s", err)
  441. continue
  442. }
  443. container := res.Container
  444. if container == "" {
  445. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM allocation query result missing 'container': %s", key)
  446. continue
  447. }
  448. var pods []*pod
  449. if thisPod, ok := podMap[key]; !ok {
  450. if uidKeys, ok := podUIDKeyMap[key]; ok {
  451. for _, uidKey := range uidKeys {
  452. thisPod, ok = podMap[uidKey]
  453. if ok {
  454. pods = append(pods, thisPod)
  455. }
  456. }
  457. } else {
  458. continue
  459. }
  460. } else {
  461. pods = []*pod{thisPod}
  462. }
  463. for _, thisPod := range pods {
  464. if _, ok := thisPod.Allocations[container]; !ok {
  465. thisPod.appendContainer(container)
  466. }
  467. ramBytes := res.Data[0].Value
  468. hours := thisPod.Allocations[container].Minutes() / 60.0
  469. thisPod.Allocations[container].RAMByteHours = ramBytes * hours
  470. node := res.Node
  471. if node == "" {
  472. log.Warnf("CostModel.ComputeAllocation: RAM allocation query result missing 'node': %s", key)
  473. continue
  474. }
  475. thisPod.Allocations[container].Properties.Node = node
  476. thisPod.Node = node
  477. }
  478. }
  479. }
  480. func applyRAMBytesRequested(podMap map[podKey]*pod, resRAMBytesRequested []*source.RAMRequestsResult, podUIDKeyMap map[podKey][]podKey) {
  481. for _, res := range resRAMBytesRequested {
  482. key, err := newResultPodKey(res.Cluster, res.Namespace, res.Pod)
  483. if err != nil {
  484. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM request result missing field: %s", err)
  485. continue
  486. }
  487. container := res.Container
  488. if container == "" {
  489. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM request query result missing 'container': %s", key)
  490. continue
  491. }
  492. var pods []*pod
  493. if thisPod, ok := podMap[key]; !ok {
  494. if uidKeys, ok := podUIDKeyMap[key]; ok {
  495. for _, uidKey := range uidKeys {
  496. thisPod, ok = podMap[uidKey]
  497. if ok {
  498. pods = append(pods, thisPod)
  499. }
  500. }
  501. } else {
  502. continue
  503. }
  504. } else {
  505. pods = []*pod{thisPod}
  506. }
  507. for _, pod := range pods {
  508. if _, ok := pod.Allocations[container]; !ok {
  509. pod.appendContainer(container)
  510. }
  511. pod.Allocations[container].RAMBytesRequestAverage = res.Data[0].Value
  512. // If RAM allocation is less than requests, set RAMByteHours to
  513. // request level.
  514. if pod.Allocations[container].RAMBytes() < res.Data[0].Value {
  515. pod.Allocations[container].RAMByteHours = res.Data[0].Value * (pod.Allocations[container].Minutes() / 60.0)
  516. }
  517. node := res.Node
  518. if node == "" {
  519. log.Warnf("CostModel.ComputeAllocation: RAM request query result missing 'node': %s", key)
  520. continue
  521. }
  522. pod.Allocations[container].Properties.Node = node
  523. pod.Node = node
  524. }
  525. }
  526. }
  527. func applyRAMBytesLimits(podMap map[podKey]*pod, resRAMBytesLimits []*source.RAMLimitsResult, podUIDKeyMap map[podKey][]podKey) {
  528. for _, res := range resRAMBytesLimits {
  529. key, err := newResultPodKey(res.Cluster, res.Namespace, res.Pod)
  530. if err != nil {
  531. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM limit result missing field: %s", err)
  532. continue
  533. }
  534. container := res.Container
  535. if container == "" {
  536. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM limit query result missing 'container': %s", key)
  537. continue
  538. }
  539. var pods []*pod
  540. if thisPod, ok := podMap[key]; !ok {
  541. if uidKeys, ok := podUIDKeyMap[key]; ok {
  542. for _, uidKey := range uidKeys {
  543. thisPod, ok = podMap[uidKey]
  544. if ok {
  545. pods = append(pods, thisPod)
  546. }
  547. }
  548. } else {
  549. continue
  550. }
  551. } else {
  552. pods = []*pod{thisPod}
  553. }
  554. for _, pod := range pods {
  555. if _, ok := pod.Allocations[container]; !ok {
  556. pod.appendContainer(container)
  557. }
  558. pod.Allocations[container].RAMBytesLimitAverage = res.Data[0].Value
  559. }
  560. }
  561. }
  562. func applyRAMBytesUsedAvg(podMap map[podKey]*pod, resRAMBytesUsedAvg []*source.RAMUsageAvgResult, podUIDKeyMap map[podKey][]podKey) {
  563. for _, res := range resRAMBytesUsedAvg {
  564. key, err := newResultPodKey(res.Cluster, res.Namespace, res.Pod)
  565. if err != nil {
  566. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM avg usage result missing field: %s", err)
  567. continue
  568. }
  569. container := res.Container
  570. if container == "" {
  571. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM usage avg query result missing 'container': %s", key)
  572. continue
  573. }
  574. var pods []*pod
  575. if thisPod, ok := podMap[key]; !ok {
  576. if uidKeys, ok := podUIDKeyMap[key]; ok {
  577. for _, uidKey := range uidKeys {
  578. thisPod, ok = podMap[uidKey]
  579. if ok {
  580. pods = append(pods, thisPod)
  581. }
  582. }
  583. } else {
  584. continue
  585. }
  586. } else {
  587. pods = []*pod{thisPod}
  588. }
  589. for _, thisPod := range pods {
  590. if _, ok := thisPod.Allocations[container]; !ok {
  591. thisPod.appendContainer(container)
  592. }
  593. thisPod.Allocations[container].RAMBytesUsageAverage = res.Data[0].Value
  594. }
  595. }
  596. }
  597. func applyRAMBytesUsedMax(podMap map[podKey]*pod, resRAMBytesUsedMax []*source.RAMUsageMaxResult, podUIDKeyMap map[podKey][]podKey) {
  598. for _, res := range resRAMBytesUsedMax {
  599. key, err := newResultPodKey(res.Cluster, res.Namespace, res.Pod)
  600. if err != nil {
  601. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM usage max result missing field: %s", err)
  602. continue
  603. }
  604. container := res.Container
  605. if container == "" {
  606. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM usage max query result missing 'container': %s", key)
  607. continue
  608. }
  609. var pods []*pod
  610. if thisPod, ok := podMap[key]; !ok {
  611. if uidKeys, ok := podUIDKeyMap[key]; ok {
  612. for _, uidKey := range uidKeys {
  613. thisPod, ok = podMap[uidKey]
  614. if ok {
  615. pods = append(pods, thisPod)
  616. }
  617. }
  618. } else {
  619. continue
  620. }
  621. } else {
  622. pods = []*pod{thisPod}
  623. }
  624. for _, thisPod := range pods {
  625. if _, ok := thisPod.Allocations[container]; !ok {
  626. thisPod.appendContainer(container)
  627. }
  628. if thisPod.Allocations[container].RawAllocationOnly == nil {
  629. thisPod.Allocations[container].RawAllocationOnly = &opencost.RawAllocationOnlyData{
  630. RAMBytesUsageMax: res.Data[0].Value,
  631. }
  632. } else {
  633. thisPod.Allocations[container].RawAllocationOnly.RAMBytesUsageMax = res.Data[0].Value
  634. }
  635. }
  636. }
  637. }
  638. // apply gpu usage average to allocations
  639. func applyGPUUsageAvg(podMap map[podKey]*pod, resGPUUsageAvg []*source.GPUsUsageAvgResult, podUIDKeyMap map[podKey][]podKey) {
  640. // Example PromQueryResult: {container="dcgmproftester12", namespace="gpu", pod="dcgmproftester3-deployment-fc89c8dd6-ph7z5"} 0.997307
  641. for _, res := range resGPUUsageAvg {
  642. key, err := newResultPodKey(res.Cluster, res.Namespace, res.Pod)
  643. if err != nil {
  644. log.DedupedWarningf(10, "CostModel.ComputeAllocation: GPU usage avg result missing field: %s", err)
  645. continue
  646. }
  647. var pods []*pod
  648. if thisPod, ok := podMap[key]; !ok {
  649. if uidKeys, ok := podUIDKeyMap[key]; ok {
  650. for _, uidKey := range uidKeys {
  651. thisPod, ok = podMap[uidKey]
  652. if ok {
  653. pods = append(pods, thisPod)
  654. }
  655. }
  656. } else {
  657. continue
  658. }
  659. } else {
  660. pods = []*pod{thisPod}
  661. }
  662. for _, thisPod := range pods {
  663. container := res.Container
  664. if container == "" {
  665. log.DedupedWarningf(10, "CostModel.ComputeAllocation: GPU usage avg query result missing 'container': %s", key)
  666. continue
  667. }
  668. if _, ok := thisPod.Allocations[container]; !ok {
  669. thisPod.appendContainer(container)
  670. }
  671. if thisPod.Allocations[container].GPUAllocation == nil {
  672. thisPod.Allocations[container].GPUAllocation = &opencost.GPUAllocation{GPUUsageAverage: &res.Data[0].Value}
  673. } else {
  674. thisPod.Allocations[container].GPUAllocation.GPUUsageAverage = &res.Data[0].Value
  675. }
  676. }
  677. }
  678. }
  679. // apply gpu usage max to allocations
  680. func applyGPUUsageMax(podMap map[podKey]*pod, resGPUUsageMax []*source.GPUsUsageMaxResult, podUIDKeyMap map[podKey][]podKey) {
  681. // Example PromQueryResult: {container="dcgmproftester12", namespace="gpu", pod="dcgmproftester3-deployment-fc89c8dd6-ph7z5"} 0.997307
  682. for _, res := range resGPUUsageMax {
  683. key, err := newResultPodKey(res.Cluster, res.Namespace, res.Pod)
  684. if err != nil {
  685. log.DedupedWarningf(10, "CostModel.ComputeAllocation: GPU usage max result missing field: %s", err)
  686. continue
  687. }
  688. var pods []*pod
  689. if thisPod, ok := podMap[key]; !ok {
  690. if uidKeys, ok := podUIDKeyMap[key]; ok {
  691. for _, uidKey := range uidKeys {
  692. thisPod, ok = podMap[uidKey]
  693. if ok {
  694. pods = append(pods, thisPod)
  695. }
  696. }
  697. } else {
  698. continue
  699. }
  700. } else {
  701. pods = []*pod{thisPod}
  702. }
  703. for _, thisPod := range pods {
  704. container := res.Container
  705. if container == "" {
  706. log.DedupedWarningf(10, "CostModel.ComputeAllocation: GPU usage max query result missing 'container': %s", key)
  707. continue
  708. }
  709. if _, ok := thisPod.Allocations[container]; !ok {
  710. thisPod.appendContainer(container)
  711. }
  712. if thisPod.Allocations[container].RawAllocationOnly == nil {
  713. thisPod.Allocations[container].RawAllocationOnly = &opencost.RawAllocationOnlyData{
  714. GPUUsageMax: &res.Data[0].Value,
  715. }
  716. } else {
  717. thisPod.Allocations[container].RawAllocationOnly.GPUUsageMax = &res.Data[0].Value
  718. }
  719. }
  720. }
  721. }
  722. // apply gpu shared data to allocations
  723. func applyGPUUsageShared(podMap map[podKey]*pod, resIsGPUShared []*source.IsGPUSharedResult, podUIDKeyMap map[podKey][]podKey) {
  724. // Example PromQueryResult: {container="dcgmproftester12", namespace="gpu", pod="dcgmproftester3-deployment-fc89c8dd6-ph7z5"} 0.997307
  725. for _, res := range resIsGPUShared {
  726. key, err := newResultPodKey(res.Cluster, res.Namespace, res.Pod)
  727. if err != nil {
  728. log.DedupedWarningf(10, "CostModel.ComputeAllocation: GPU usage avg/max result missing field: %s", err)
  729. continue
  730. }
  731. var pods []*pod
  732. if thisPod, ok := podMap[key]; !ok {
  733. if uidKeys, ok := podUIDKeyMap[key]; ok {
  734. for _, uidKey := range uidKeys {
  735. thisPod, ok = podMap[uidKey]
  736. if ok {
  737. pods = append(pods, thisPod)
  738. }
  739. }
  740. } else {
  741. continue
  742. }
  743. } else {
  744. pods = []*pod{thisPod}
  745. }
  746. for _, thisPod := range pods {
  747. container := res.Container
  748. if container == "" {
  749. log.DedupedWarningf(10, "CostModel.ComputeAllocation: GPU is shared query result missing 'container': %s", key)
  750. continue
  751. }
  752. if _, ok := thisPod.Allocations[container]; !ok {
  753. thisPod.appendContainer(container)
  754. }
  755. // if a container is using a GPU and it is shared, isGPUShared will be true
  756. // if a container is using GPU and it is NOT shared, isGPUShared will be false
  757. // if a container is NOT using a GPU, isGPUShared will be null
  758. if res.Resource == "nvidia_com_gpu_shared" {
  759. trueVal := true
  760. if res.Data[0].Value == 1 {
  761. if thisPod.Allocations[container].GPUAllocation == nil {
  762. thisPod.Allocations[container].GPUAllocation = &opencost.GPUAllocation{IsGPUShared: &trueVal}
  763. } else {
  764. thisPod.Allocations[container].GPUAllocation.IsGPUShared = &trueVal
  765. }
  766. }
  767. } else if res.Resource == "nvidia_com_gpu" {
  768. falseVal := false
  769. if res.Data[0].Value == 1 {
  770. if thisPod.Allocations[container].GPUAllocation == nil {
  771. thisPod.Allocations[container].GPUAllocation = &opencost.GPUAllocation{IsGPUShared: &falseVal}
  772. } else {
  773. thisPod.Allocations[container].GPUAllocation.IsGPUShared = &falseVal
  774. }
  775. }
  776. } else {
  777. continue
  778. }
  779. }
  780. }
  781. }
  782. // apply gpu info to allocations
  783. func applyGPUInfo(podMap map[podKey]*pod, resGPUInfo []*source.GPUInfoResult, podUIDKeyMap map[podKey][]podKey) {
  784. // Example PromQueryResult: {container="dcgmproftester12", namespace="gpu", pod="dcgmproftester3-deployment-fc89c8dd6-ph7z5"} 0.997307
  785. for _, res := range resGPUInfo {
  786. key, err := newResultPodKey(res.Cluster, res.Namespace, res.Pod)
  787. if err != nil {
  788. log.DedupedWarningf(10, "CostModel.ComputeAllocation: GPU Info query result missing field: %s", err)
  789. continue
  790. }
  791. var pods []*pod
  792. if thisPod, ok := podMap[key]; !ok {
  793. if uidKeys, ok := podUIDKeyMap[key]; ok {
  794. for _, uidKey := range uidKeys {
  795. thisPod, ok = podMap[uidKey]
  796. if ok {
  797. pods = append(pods, thisPod)
  798. }
  799. }
  800. } else {
  801. continue
  802. }
  803. } else {
  804. pods = []*pod{thisPod}
  805. }
  806. for _, thisPod := range pods {
  807. container := res.Container
  808. if container == "" {
  809. log.DedupedWarningf(10, "CostModel.ComputeAllocation: GPU Info query result missing 'container': %s", key)
  810. continue
  811. }
  812. if _, ok := thisPod.Allocations[container]; !ok {
  813. thisPod.appendContainer(container)
  814. }
  815. // DCGM_FI_PROF_GR_ENGINE_ACTIVE metric is a float between 0-1.
  816. if thisPod.Allocations[container].GPUAllocation == nil {
  817. thisPod.Allocations[container].GPUAllocation = &opencost.GPUAllocation{
  818. GPUDevice: getSanitizedDeviceName(res.Device),
  819. GPUModel: res.ModelName,
  820. GPUUUID: res.UUID,
  821. }
  822. } else {
  823. thisPod.Allocations[container].GPUAllocation.GPUDevice = getSanitizedDeviceName(res.Device)
  824. thisPod.Allocations[container].GPUAllocation.GPUModel = res.ModelName
  825. thisPod.Allocations[container].GPUAllocation.GPUUUID = res.UUID
  826. }
  827. }
  828. }
  829. }
  830. func applyGPUsAllocated(podMap map[podKey]*pod, resGPUsRequested []*source.GPUsRequestedResult, resGPUsAllocated []*source.GPUsAllocatedResult, podUIDKeyMap map[podKey][]podKey) {
  831. if len(resGPUsAllocated) > 0 { // Use the new query, when it's become available in a window
  832. resGPUsRequested = resGPUsAllocated
  833. }
  834. for _, res := range resGPUsRequested {
  835. key, err := newResultPodKey(res.Cluster, res.Namespace, res.Pod)
  836. if err != nil {
  837. log.DedupedWarningf(10, "CostModel.ComputeAllocation: GPU request result missing field: %s", err)
  838. continue
  839. }
  840. container := res.Container
  841. if container == "" {
  842. log.DedupedWarningf(10, "CostModel.ComputeAllocation: GPU request query result missing 'container': %s", key)
  843. continue
  844. }
  845. var pods []*pod
  846. if thisPod, ok := podMap[key]; !ok {
  847. if uidKeys, ok := podUIDKeyMap[key]; ok {
  848. for _, uidKey := range uidKeys {
  849. thisPod, ok = podMap[uidKey]
  850. if ok {
  851. pods = append(pods, thisPod)
  852. }
  853. }
  854. } else {
  855. continue
  856. }
  857. } else {
  858. pods = []*pod{thisPod}
  859. }
  860. for _, thisPod := range pods {
  861. if _, ok := thisPod.Allocations[container]; !ok {
  862. thisPod.appendContainer(container)
  863. }
  864. hrs := thisPod.Allocations[container].Minutes() / 60.0
  865. thisPod.Allocations[container].GPUHours = res.Data[0].Value * hrs
  866. // For now, it will always be the case that Request==Allocation. If
  867. // you would like to use a GPU you need to request the full GPU.
  868. // Therefore max(usage,request) will always equal request. In the
  869. // future this may need to be refactored when building support for
  870. // GPU Time Slicing.
  871. if thisPod.Allocations[container].GPUAllocation == nil {
  872. thisPod.Allocations[container].GPUAllocation = &opencost.GPUAllocation{
  873. GPURequestAverage: &res.Data[0].Value,
  874. }
  875. } else {
  876. thisPod.Allocations[container].GPUAllocation.GPURequestAverage = &res.Data[0].Value
  877. }
  878. }
  879. }
  880. }
  881. func applyNetworkTotals(podMap map[podKey]*pod, resNetworkTransferBytes []*source.NetTransferBytesResult, resNetworkReceiveBytes []*source.NetReceiveBytesResult, podUIDKeyMap map[podKey][]podKey) {
  882. for _, res := range resNetworkTransferBytes {
  883. podKey, err := newResultPodKey(res.Cluster, res.Namespace, res.Pod)
  884. if err != nil {
  885. log.DedupedWarningf(10, "CostModel.ComputeAllocation: Network Transfer Bytes query result missing field: %s", err)
  886. continue
  887. }
  888. var pods []*pod
  889. if thisPod, ok := podMap[podKey]; !ok {
  890. if uidKeys, ok := podUIDKeyMap[podKey]; ok {
  891. for _, uidKey := range uidKeys {
  892. thisPod, ok = podMap[uidKey]
  893. if ok {
  894. pods = append(pods, thisPod)
  895. }
  896. }
  897. } else {
  898. continue
  899. }
  900. } else {
  901. pods = []*pod{thisPod}
  902. }
  903. for _, thisPod := range pods {
  904. for _, alloc := range thisPod.Allocations {
  905. alloc.NetworkTransferBytes = res.Data[0].Value / float64(len(thisPod.Allocations)) / float64(len(pods))
  906. }
  907. }
  908. }
  909. for _, res := range resNetworkReceiveBytes {
  910. podKey, err := newResultPodKey(res.Cluster, res.Namespace, res.Pod)
  911. if err != nil {
  912. log.DedupedWarningf(10, "CostModel.ComputeAllocation: Network Receive Bytes query result missing field: %s", err)
  913. continue
  914. }
  915. var pods []*pod
  916. if thisPod, ok := podMap[podKey]; !ok {
  917. if uidKeys, ok := podUIDKeyMap[podKey]; ok {
  918. for _, uidKey := range uidKeys {
  919. thisPod, ok = podMap[uidKey]
  920. if ok {
  921. pods = append(pods, thisPod)
  922. }
  923. }
  924. } else {
  925. continue
  926. }
  927. } else {
  928. pods = []*pod{thisPod}
  929. }
  930. for _, thisPod := range pods {
  931. for _, alloc := range thisPod.Allocations {
  932. alloc.NetworkReceiveBytes = res.Data[0].Value / float64(len(thisPod.Allocations)) / float64(len(pods))
  933. }
  934. }
  935. }
  936. }
  937. func applyCrossZoneNetworkAllocation(alloc *opencost.Allocation, networkSubCost float64) {
  938. alloc.NetworkCrossZoneCost = networkSubCost
  939. }
  940. func applyCrossRegionNetworkAllocation(alloc *opencost.Allocation, networkSubCost float64) {
  941. alloc.NetworkCrossRegionCost = networkSubCost
  942. }
  943. func applyInternetNetworkAllocation(alloc *opencost.Allocation, networkSubCost float64) {
  944. alloc.NetworkInternetCost = networkSubCost
  945. }
  946. func applyNetworkAllocation(podMap map[podKey]*pod, resNetworkGiB []*source.NetworkGiBResult, resNetworkCostPerGiB []*source.NetworkPricePerGiBResult, podUIDKeyMap map[podKey][]podKey, applyCostFunc func(*opencost.Allocation, float64)) {
  947. costPerGiBByCluster := map[string]float64{}
  948. for _, res := range resNetworkCostPerGiB {
  949. cluster := res.Cluster
  950. if cluster == "" {
  951. cluster = coreenv.GetClusterID()
  952. }
  953. costPerGiBByCluster[cluster] = res.Data[0].Value
  954. }
  955. for _, res := range resNetworkGiB {
  956. podKey, err := newResultPodKey(res.Cluster, res.Namespace, res.Pod)
  957. if err != nil {
  958. log.DedupedWarningf(10, "CostModel.ComputeAllocation: Network allocation query result missing field: %s", err)
  959. continue
  960. }
  961. var pods []*pod
  962. if thisPod, ok := podMap[podKey]; !ok {
  963. if uidKeys, ok := podUIDKeyMap[podKey]; ok {
  964. for _, uidKey := range uidKeys {
  965. thisPod, ok = podMap[uidKey]
  966. if ok {
  967. pods = append(pods, thisPod)
  968. }
  969. }
  970. } else {
  971. continue
  972. }
  973. } else {
  974. pods = []*pod{thisPod}
  975. }
  976. for _, thisPod := range pods {
  977. for _, alloc := range thisPod.Allocations {
  978. gib := res.Data[0].Value / float64(len(thisPod.Allocations))
  979. costPerGiB := costPerGiBByCluster[podKey.Cluster]
  980. currentNetworkSubCost := gib * costPerGiB / float64(len(pods))
  981. applyCostFunc(alloc, currentNetworkSubCost)
  982. alloc.NetworkCost += currentNetworkSubCost
  983. }
  984. }
  985. }
  986. }
  987. func resToNodeLabels(resNodeLabels []*source.NodeLabelsResult) map[nodeKey]map[string]string {
  988. nodeLabels := map[nodeKey]map[string]string{}
  989. for _, res := range resNodeLabels {
  990. nodeKey, err := newResultNodeKey(res.Cluster, res.Node)
  991. if err != nil {
  992. continue
  993. }
  994. if _, ok := nodeLabels[nodeKey]; !ok {
  995. nodeLabels[nodeKey] = map[string]string{}
  996. }
  997. labels := res.Labels
  998. // labels are retrieved from prometheus here so it will be in prometheus sanitized state
  999. // e.g. topology.kubernetes.io/zone => topology_kubernetes_io_zone
  1000. for labelKey, labelValue := range labels {
  1001. nodeLabels[nodeKey][labelKey] = labelValue
  1002. }
  1003. }
  1004. return nodeLabels
  1005. }
  1006. func resToNamespaceLabels(resNamespaceLabels []*source.NamespaceLabelsResult) map[namespaceKey]map[string]string {
  1007. namespaceLabels := map[namespaceKey]map[string]string{}
  1008. for _, res := range resNamespaceLabels {
  1009. nsKey, err := newResultNamespaceKey(res.Cluster, res.Namespace)
  1010. if err != nil {
  1011. continue
  1012. }
  1013. if _, ok := namespaceLabels[nsKey]; !ok {
  1014. namespaceLabels[nsKey] = map[string]string{}
  1015. }
  1016. for k, l := range res.Labels {
  1017. namespaceLabels[nsKey][k] = l
  1018. }
  1019. }
  1020. return namespaceLabels
  1021. }
  1022. func resToPodLabels(resPodLabels []*source.PodLabelsResult, podUIDKeyMap map[podKey][]podKey, ingestPodUID bool) map[podKey]map[string]string {
  1023. podLabels := map[podKey]map[string]string{}
  1024. for _, res := range resPodLabels {
  1025. key, err := newResultPodKey(res.Cluster, res.Namespace, res.Pod)
  1026. if err != nil {
  1027. continue
  1028. }
  1029. var keys []podKey
  1030. if ingestPodUID {
  1031. keys = podUIDKeyMap[key]
  1032. } else {
  1033. keys = []podKey{key}
  1034. }
  1035. for _, key := range keys {
  1036. if _, ok := podLabels[key]; !ok {
  1037. podLabels[key] = map[string]string{}
  1038. }
  1039. for k, l := range res.Labels {
  1040. podLabels[key][k] = l
  1041. }
  1042. }
  1043. }
  1044. return podLabels
  1045. }
  1046. func resToNamespaceAnnotations(resNamespaceAnnotations []*source.NamespaceAnnotationsResult) map[string]map[string]string {
  1047. namespaceAnnotations := map[string]map[string]string{}
  1048. for _, res := range resNamespaceAnnotations {
  1049. namespace := res.Namespace
  1050. if namespace == "" {
  1051. continue
  1052. }
  1053. if _, ok := namespaceAnnotations[namespace]; !ok {
  1054. namespaceAnnotations[namespace] = map[string]string{}
  1055. }
  1056. for k, l := range res.Annotations {
  1057. namespaceAnnotations[namespace][k] = l
  1058. }
  1059. }
  1060. return namespaceAnnotations
  1061. }
  1062. func resToPodAnnotations(resPodAnnotations []*source.PodAnnotationsResult, podUIDKeyMap map[podKey][]podKey, ingestPodUID bool) map[podKey]map[string]string {
  1063. podAnnotations := map[podKey]map[string]string{}
  1064. for _, res := range resPodAnnotations {
  1065. key, err := newResultPodKey(res.Cluster, res.Namespace, res.Pod)
  1066. if err != nil {
  1067. continue
  1068. }
  1069. var keys []podKey
  1070. if ingestPodUID {
  1071. keys = podUIDKeyMap[key]
  1072. } else {
  1073. keys = []podKey{key}
  1074. }
  1075. for _, key := range keys {
  1076. if _, ok := podAnnotations[key]; !ok {
  1077. podAnnotations[key] = map[string]string{}
  1078. }
  1079. for k, l := range res.Annotations {
  1080. podAnnotations[key][k] = l
  1081. }
  1082. }
  1083. }
  1084. return podAnnotations
  1085. }
  1086. func applyLabels(podMap map[podKey]*pod, nodeLabels map[nodeKey]map[string]string, namespaceLabels map[namespaceKey]map[string]string, podLabels map[podKey]map[string]string) {
  1087. for podKey, pod := range podMap {
  1088. for _, alloc := range pod.Allocations {
  1089. allocLabels := alloc.Properties.Labels
  1090. if allocLabels == nil {
  1091. allocLabels = make(map[string]string)
  1092. }
  1093. nsLabels := alloc.Properties.NamespaceLabels
  1094. if nsLabels == nil {
  1095. nsLabels = make(map[string]string)
  1096. }
  1097. // Apply node labels first, then namespace labels, then pod labels
  1098. // so that pod labels overwrite namespace labels, which overwrite
  1099. // node labels.
  1100. if nodeLabels != nil {
  1101. nodeKey := newNodeKey(pod.Key.Cluster, pod.Node)
  1102. if labels, ok := nodeLabels[nodeKey]; ok {
  1103. for k, v := range labels {
  1104. allocLabels[k] = v
  1105. }
  1106. }
  1107. }
  1108. nsKey := podKey.namespaceKey
  1109. if labels, ok := namespaceLabels[nsKey]; ok {
  1110. for k, v := range labels {
  1111. allocLabels[k] = v
  1112. nsLabels[k] = v
  1113. }
  1114. }
  1115. if labels, ok := podLabels[podKey]; ok {
  1116. for k, v := range labels {
  1117. allocLabels[k] = v
  1118. }
  1119. }
  1120. alloc.Properties.Labels = allocLabels
  1121. alloc.Properties.NamespaceLabels = nsLabels
  1122. }
  1123. }
  1124. }
  1125. func applyAnnotations(podMap map[podKey]*pod, namespaceAnnotations map[string]map[string]string, podAnnotations map[podKey]map[string]string) {
  1126. for key, pod := range podMap {
  1127. for _, alloc := range pod.Allocations {
  1128. allocAnnotations := alloc.Properties.Annotations
  1129. if allocAnnotations == nil {
  1130. allocAnnotations = make(map[string]string)
  1131. }
  1132. nsAnnotations := alloc.Properties.NamespaceAnnotations
  1133. if nsAnnotations == nil {
  1134. nsAnnotations = make(map[string]string)
  1135. }
  1136. // Apply namespace annotations first, then pod annotations so that
  1137. // pod labels overwrite namespace labels.
  1138. if labels, ok := namespaceAnnotations[key.Namespace]; ok {
  1139. for k, v := range labels {
  1140. allocAnnotations[k] = v
  1141. nsAnnotations[k] = v
  1142. }
  1143. }
  1144. if labels, ok := podAnnotations[key]; ok {
  1145. for k, v := range labels {
  1146. allocAnnotations[k] = v
  1147. }
  1148. }
  1149. alloc.Properties.Annotations = allocAnnotations
  1150. alloc.Properties.NamespaceAnnotations = nsAnnotations
  1151. }
  1152. }
  1153. }
  1154. func resToDeploymentLabels(resDeploymentLabels []*source.DeploymentLabelsResult) map[controllerKey]map[string]string {
  1155. deploymentLabels := map[controllerKey]map[string]string{}
  1156. for _, res := range resDeploymentLabels {
  1157. controllerKey, err := newResultControllerKey(res.Cluster, res.Namespace, res.Deployment, "deployment")
  1158. if err != nil {
  1159. continue
  1160. }
  1161. if _, ok := deploymentLabels[controllerKey]; !ok {
  1162. deploymentLabels[controllerKey] = map[string]string{}
  1163. }
  1164. for k, l := range res.Labels {
  1165. deploymentLabels[controllerKey][k] = l
  1166. }
  1167. }
  1168. // Prune duplicate deployments. That is, if the same deployment exists with
  1169. // hyphens instead of underscores, keep the one that uses hyphens.
  1170. for key := range deploymentLabels {
  1171. if strings.Contains(key.Controller, "_") {
  1172. duplicateController := strings.Replace(key.Controller, "_", "-", -1)
  1173. duplicateKey := newControllerKey(key.Cluster, key.Namespace, key.ControllerKind, duplicateController)
  1174. if _, ok := deploymentLabels[duplicateKey]; ok {
  1175. delete(deploymentLabels, key)
  1176. }
  1177. }
  1178. }
  1179. return deploymentLabels
  1180. }
  1181. func resToStatefulSetLabels(resStatefulSetLabels []*source.StatefulSetLabelsResult) map[controllerKey]map[string]string {
  1182. statefulSetLabels := map[controllerKey]map[string]string{}
  1183. for _, res := range resStatefulSetLabels {
  1184. controllerKey, err := newResultControllerKey(res.Cluster, res.Namespace, res.StatefulSet, "statefulset")
  1185. if err != nil {
  1186. continue
  1187. }
  1188. if _, ok := statefulSetLabels[controllerKey]; !ok {
  1189. statefulSetLabels[controllerKey] = map[string]string{}
  1190. }
  1191. for k, l := range res.Labels {
  1192. statefulSetLabels[controllerKey][k] = l
  1193. }
  1194. }
  1195. // Prune duplicate stateful sets. That is, if the same stateful set exists
  1196. // with hyphens instead of underscores, keep the one that uses hyphens.
  1197. for key := range statefulSetLabels {
  1198. if strings.Contains(key.Controller, "_") {
  1199. duplicateController := strings.Replace(key.Controller, "_", "-", -1)
  1200. duplicateKey := newControllerKey(key.Cluster, key.Namespace, key.ControllerKind, duplicateController)
  1201. if _, ok := statefulSetLabels[duplicateKey]; ok {
  1202. delete(statefulSetLabels, key)
  1203. }
  1204. }
  1205. }
  1206. return statefulSetLabels
  1207. }
  1208. func labelsToPodControllerMap(podLabels map[podKey]map[string]string, controllerLabels map[controllerKey]map[string]string) map[podKey]controllerKey {
  1209. podControllerMap := map[podKey]controllerKey{}
  1210. // For each controller, turn the labels into a selector and attempt to
  1211. // match it with each set of pod labels. A match indicates that the pod
  1212. // belongs to the controller.
  1213. for cKey, cLabels := range controllerLabels {
  1214. selector := labels.Set(cLabels).AsSelectorPreValidated()
  1215. for pKey, pLabels := range podLabels {
  1216. // If the pod is in a different cluster or namespace, there is
  1217. // no need to compare the labels.
  1218. if cKey.Cluster != pKey.Cluster || cKey.Namespace != pKey.Namespace {
  1219. continue
  1220. }
  1221. podLabelSet := labels.Set(pLabels)
  1222. if selector.Matches(podLabelSet) {
  1223. if _, ok := podControllerMap[pKey]; ok {
  1224. log.DedupedWarningf(5, "CostModel.ComputeAllocation: PodControllerMap match already exists: %s matches %s and %s", pKey, podControllerMap[pKey], cKey)
  1225. }
  1226. podControllerMap[pKey] = cKey
  1227. }
  1228. }
  1229. }
  1230. return podControllerMap
  1231. }
  1232. func resToPodDaemonSetMap(resDaemonSetLabels []*source.DaemonSetLabelsResult, podUIDKeyMap map[podKey][]podKey, ingestPodUID bool) map[podKey]controllerKey {
  1233. daemonSetLabels := map[podKey]controllerKey{}
  1234. for _, res := range resDaemonSetLabels {
  1235. controllerKey, err := newResultControllerKey(res.Cluster, res.Namespace, res.DaemonSet, "daemonset")
  1236. if err != nil {
  1237. continue
  1238. }
  1239. pod := res.Pod
  1240. if pod == "" {
  1241. log.Warnf("CostModel.ComputeAllocation: DaemonSetLabel result without pod: %s", controllerKey)
  1242. }
  1243. key := newPodKey(controllerKey.Cluster, controllerKey.Namespace, pod)
  1244. var keys []podKey
  1245. if ingestPodUID {
  1246. if uidKeys, ok := podUIDKeyMap[key]; ok {
  1247. keys = append(keys, uidKeys...)
  1248. }
  1249. } else {
  1250. keys = []podKey{key}
  1251. }
  1252. for _, key := range keys {
  1253. daemonSetLabels[key] = controllerKey
  1254. }
  1255. }
  1256. return daemonSetLabels
  1257. }
  1258. func resToPodJobMap(resJobLabels []*source.JobLabelsResult, podUIDKeyMap map[podKey][]podKey, ingestPodUID bool) map[podKey]controllerKey {
  1259. jobLabels := map[podKey]controllerKey{}
  1260. for _, res := range resJobLabels {
  1261. controllerKey, err := newResultControllerKey(res.Cluster, res.Namespace, res.Job, "job")
  1262. if err != nil {
  1263. continue
  1264. }
  1265. // Convert the name of Jobs generated by CronJobs to the name of the
  1266. // CronJob by stripping the timestamp off the end.
  1267. match := isCron.FindStringSubmatch(controllerKey.Controller)
  1268. if match != nil {
  1269. controllerKey.Controller = match[1]
  1270. }
  1271. pod := res.Pod
  1272. if pod == "" {
  1273. log.Warnf("CostModel.ComputeAllocation: JobLabel result without pod: %s", controllerKey)
  1274. }
  1275. key := newPodKey(controllerKey.Cluster, controllerKey.Namespace, pod)
  1276. var keys []podKey
  1277. if ingestPodUID {
  1278. if uidKeys, ok := podUIDKeyMap[key]; ok {
  1279. keys = append(keys, uidKeys...)
  1280. }
  1281. } else {
  1282. keys = []podKey{key}
  1283. }
  1284. for _, key := range keys {
  1285. jobLabels[key] = controllerKey
  1286. }
  1287. }
  1288. return jobLabels
  1289. }
  1290. func resToPodReplicaSetMap(resPodsWithReplicaSetOwner []*source.PodsWithReplicaSetOwnerResult, resReplicaSetsWithoutOwners []*source.ReplicaSetsWithoutOwnersResult, resReplicaSetsWithRolloutOwner []*source.ReplicaSetsWithRolloutResult, podUIDKeyMap map[podKey][]podKey, ingestPodUID bool) map[podKey]controllerKey {
  1291. // Build out set of ReplicaSets that have no owners, themselves, such that
  1292. // the ReplicaSet should be used as the owner of the Pods it controls.
  1293. // (This should exclude, for example, ReplicaSets that are controlled by
  1294. // Deployments, in which case the Deployment should be the pod's owner.)
  1295. // Additionally, add to this set of ReplicaSets those ReplicaSets that
  1296. // are owned by a Rollout
  1297. replicaSets := map[controllerKey]struct{}{}
  1298. // Create unowned ReplicaSet controller keys
  1299. for _, res := range resReplicaSetsWithoutOwners {
  1300. controllerKey, err := newResultControllerKey(res.Cluster, res.Namespace, res.ReplicaSet, "replicaset")
  1301. if err != nil {
  1302. continue
  1303. }
  1304. replicaSets[controllerKey] = struct{}{}
  1305. }
  1306. // Create Rollout-owned ReplicaSet controller keys
  1307. for _, res := range resReplicaSetsWithRolloutOwner {
  1308. controllerKey, err := newResultControllerKey(res.Cluster, res.Namespace, res.ReplicaSet, "rollout")
  1309. if err != nil {
  1310. continue
  1311. }
  1312. replicaSets[controllerKey] = struct{}{}
  1313. }
  1314. // Create the mapping of Pods to ReplicaSets, ignoring any ReplicaSets that
  1315. // do not appear in the set of unowned/Rollout-owned ReplicaSets above.
  1316. podToReplicaSet := map[podKey]controllerKey{}
  1317. for _, res := range resPodsWithReplicaSetOwner {
  1318. // First, check if this pod is owned by an unowned ReplicaSet
  1319. controllerKey, err := newResultControllerKey(res.Cluster, res.Namespace, res.ReplicaSet, "replicaset")
  1320. if err != nil {
  1321. continue
  1322. } else if _, ok := replicaSets[controllerKey]; !ok {
  1323. // If the pod is not owned by an unowned ReplicaSet, check if
  1324. // it's owned by a Rollout-owned ReplicaSet
  1325. controllerKey, err = newResultControllerKey(res.Cluster, res.Namespace, res.ReplicaSet, "rollout")
  1326. if err != nil {
  1327. continue
  1328. } else if _, ok := replicaSets[controllerKey]; !ok {
  1329. continue
  1330. }
  1331. }
  1332. pod := res.Pod
  1333. if pod == "" {
  1334. log.Warnf("CostModel.ComputeAllocation: ReplicaSet result without pod: %s", controllerKey)
  1335. }
  1336. key := newPodKey(controllerKey.Cluster, controllerKey.Namespace, pod)
  1337. var keys []podKey
  1338. if ingestPodUID {
  1339. if uidKeys, ok := podUIDKeyMap[key]; ok {
  1340. keys = append(keys, uidKeys...)
  1341. }
  1342. } else {
  1343. keys = []podKey{key}
  1344. }
  1345. for _, key := range keys {
  1346. podToReplicaSet[key] = controllerKey
  1347. }
  1348. }
  1349. return podToReplicaSet
  1350. }
  1351. func applyControllersToPods(podMap map[podKey]*pod, podControllerMap map[podKey]controllerKey) {
  1352. for key, pod := range podMap {
  1353. for _, alloc := range pod.Allocations {
  1354. if controllerKey, ok := podControllerMap[key]; ok {
  1355. alloc.Properties.ControllerKind = controllerKey.ControllerKind
  1356. alloc.Properties.Controller = controllerKey.Controller
  1357. }
  1358. }
  1359. }
  1360. }
  1361. /* Service Helpers */
  1362. func getServiceLabels(resServiceLabels []*source.ServiceLabelsResult) map[serviceKey]map[string]string {
  1363. serviceLabels := map[serviceKey]map[string]string{}
  1364. for _, res := range resServiceLabels {
  1365. serviceKey, err := newResultServiceKey(res.Cluster, res.Namespace, res.Service)
  1366. if err != nil {
  1367. continue
  1368. }
  1369. if _, ok := serviceLabels[serviceKey]; !ok {
  1370. serviceLabels[serviceKey] = map[string]string{}
  1371. }
  1372. for k, l := range res.Labels {
  1373. serviceLabels[serviceKey][k] = l
  1374. }
  1375. }
  1376. // Prune duplicate services. That is, if the same service exists with
  1377. // hyphens instead of underscores, keep the one that uses hyphens.
  1378. for key := range serviceLabels {
  1379. if strings.Contains(key.Service, "_") {
  1380. duplicateService := strings.Replace(key.Service, "_", "-", -1)
  1381. duplicateKey := newServiceKey(key.Cluster, key.Namespace, duplicateService)
  1382. if _, ok := serviceLabels[duplicateKey]; ok {
  1383. delete(serviceLabels, key)
  1384. }
  1385. }
  1386. }
  1387. return serviceLabels
  1388. }
  1389. func applyServicesToPods(podMap map[podKey]*pod, podLabels map[podKey]map[string]string, allocsByService map[serviceKey][]*opencost.Allocation, serviceLabels map[serviceKey]map[string]string) {
  1390. podServicesMap := map[podKey][]serviceKey{}
  1391. // For each service, turn the labels into a selector and attempt to
  1392. // match it with each set of pod labels. A match indicates that the pod
  1393. // belongs to the service.
  1394. for sKey, sLabels := range serviceLabels {
  1395. selector := labels.Set(sLabels).AsSelectorPreValidated()
  1396. for pKey, pLabels := range podLabels {
  1397. // If the pod is in a different cluster or namespace, there is
  1398. // no need to compare the labels.
  1399. if sKey.Cluster != pKey.Cluster || sKey.Namespace != pKey.Namespace {
  1400. continue
  1401. }
  1402. podLabelSet := labels.Set(pLabels)
  1403. if selector.Matches(podLabelSet) {
  1404. if _, ok := podServicesMap[pKey]; !ok {
  1405. podServicesMap[pKey] = []serviceKey{}
  1406. }
  1407. podServicesMap[pKey] = append(podServicesMap[pKey], sKey)
  1408. }
  1409. }
  1410. }
  1411. // For each allocation in each pod, attempt to find and apply the list of
  1412. // services associated with the allocation's pod.
  1413. for key, pod := range podMap {
  1414. for _, alloc := range pod.Allocations {
  1415. if sKeys, ok := podServicesMap[key]; ok {
  1416. services := []string{}
  1417. for _, sKey := range sKeys {
  1418. services = append(services, sKey.Service)
  1419. allocsByService[sKey] = append(allocsByService[sKey], alloc)
  1420. }
  1421. alloc.Properties.Services = services
  1422. }
  1423. }
  1424. }
  1425. }
  1426. func getLoadBalancerCosts(lbMap map[serviceKey]*lbCost, resLBCost []*source.LBPricePerHrResult, resLBActiveMins []*source.LBActiveMinutesResult, resolution time.Duration, window opencost.Window) {
  1427. for _, res := range resLBActiveMins {
  1428. serviceKey, err := newResultServiceKey(res.Cluster, res.Namespace, res.Service)
  1429. if err != nil || len(res.Data) == 0 {
  1430. continue
  1431. }
  1432. // load balancers have interpolation for costs, we don't need to offset the resolution
  1433. lbStart, lbEnd := calculateStartAndEnd(res.Data, resolution, window)
  1434. if lbStart.IsZero() || lbEnd.IsZero() {
  1435. log.Warnf("CostModel.ComputeAllocation: pvc %s has no running time", serviceKey)
  1436. }
  1437. lbMap[serviceKey] = &lbCost{
  1438. Start: lbStart,
  1439. End: lbEnd,
  1440. }
  1441. }
  1442. for _, res := range resLBCost {
  1443. serviceKey, err := newResultServiceKey(res.Cluster, res.Namespace, res.Service)
  1444. if err != nil {
  1445. continue
  1446. }
  1447. // get the ingress IP to determine if this is a private LB
  1448. ip := res.IngressIP
  1449. if ip == "" {
  1450. log.Warnf("error getting ingress ip for key %s: %v, skipping", serviceKey, err)
  1451. // do not count the time that the service was being created or deleted
  1452. // ingress IP will be empty string
  1453. // only add cost to allocation when external IP is provisioned
  1454. continue
  1455. }
  1456. // Apply cost as price-per-hour * hours
  1457. if lb, ok := lbMap[serviceKey]; ok {
  1458. lbPricePerHr := res.Data[0].Value
  1459. // interpolate any missing data
  1460. resolutionHours := resolution.Hours()
  1461. resultHours := lb.End.Sub(lb.Start).Hours()
  1462. scaleFactor := (resolutionHours + resultHours) / resultHours
  1463. // after scaling, we can adjust the timings to reflect the interpolated data
  1464. lb.End = lb.End.Add(resolution)
  1465. lb.TotalCost += lbPricePerHr * resultHours * scaleFactor
  1466. lb.Ip = ip
  1467. lb.Private = privateIPCheck(ip)
  1468. } else {
  1469. log.DedupedWarningf(20, "CostModel: found minutes for key that does not exist: %s", serviceKey)
  1470. }
  1471. }
  1472. }
  1473. func applyLoadBalancersToPods(window opencost.Window, podMap map[podKey]*pod, lbMap map[serviceKey]*lbCost, allocsByService map[serviceKey][]*opencost.Allocation) {
  1474. for sKey, lb := range lbMap {
  1475. totalHours := 0.0
  1476. allocHours := make(map[*opencost.Allocation]float64)
  1477. allocs, ok := allocsByService[sKey]
  1478. // if there are no allocations using the service, add its cost to the Unmounted pod for its cluster
  1479. if !ok {
  1480. pod := getUnmountedPodForCluster(window, podMap, sKey.Cluster)
  1481. pod.Allocations[opencost.UnmountedSuffix].LoadBalancerCost += lb.TotalCost
  1482. pod.Allocations[opencost.UnmountedSuffix].Properties.Services = append(pod.Allocations[opencost.UnmountedSuffix].Properties.Services, sKey.Service)
  1483. }
  1484. // Add portion of load balancing cost to each allocation
  1485. // proportional to the total number of hours allocations used the load balancer
  1486. for _, alloc := range allocs {
  1487. // Determine the (start, end) of the relationship between the
  1488. // given lbCost and the associated Allocation so that a precise
  1489. // number of hours can be used to compute cumulative cost.
  1490. s, e := alloc.Start, alloc.End
  1491. if lb.Start.After(alloc.Start) {
  1492. s = lb.Start
  1493. }
  1494. if lb.End.Before(alloc.End) {
  1495. e = lb.End
  1496. }
  1497. hours := e.Sub(s).Hours()
  1498. // A negative number of hours signifies no overlap between the windows
  1499. if hours > 0 {
  1500. totalHours += hours
  1501. allocHours[alloc] = hours
  1502. }
  1503. }
  1504. // Distribute cost of service once total hours is calculated
  1505. for alloc, hours := range allocHours {
  1506. alloc.LoadBalancerCost += lb.TotalCost * hours / totalHours
  1507. }
  1508. for _, alloc := range allocs {
  1509. // reocord the hours overlapped with the allocation for the load balancer
  1510. // if there was overlap. Otherwise, record a 0.0.
  1511. // TODO: Do we really want to include load balancers that have 0 overlap
  1512. // TODO: hours with the allocation?
  1513. var hours float64 = 0.0
  1514. if _, ok := allocHours[alloc]; ok {
  1515. hours = allocHours[alloc]
  1516. }
  1517. if alloc.LoadBalancers == nil {
  1518. alloc.LoadBalancers = opencost.LbAllocations{}
  1519. }
  1520. if _, found := alloc.LoadBalancers[sKey.String()]; found {
  1521. alloc.LoadBalancers[sKey.String()].Cost += alloc.LoadBalancerCost
  1522. alloc.LoadBalancers[sKey.String()].Hours += hours
  1523. } else {
  1524. alloc.LoadBalancers[sKey.String()] = &opencost.LbAllocation{
  1525. Service: sKey.Namespace + "/" + sKey.Service,
  1526. Cost: alloc.LoadBalancerCost,
  1527. Private: lb.Private,
  1528. Ip: lb.Ip,
  1529. Hours: hours,
  1530. }
  1531. }
  1532. }
  1533. // If there was no overlap apply to Unmounted pod
  1534. if len(allocHours) == 0 {
  1535. pod := getUnmountedPodForCluster(window, podMap, sKey.Cluster)
  1536. pod.Allocations[opencost.UnmountedSuffix].LoadBalancerCost += lb.TotalCost
  1537. pod.Allocations[opencost.UnmountedSuffix].Properties.Services = append(pod.Allocations[opencost.UnmountedSuffix].Properties.Services, sKey.Service)
  1538. }
  1539. }
  1540. }
  1541. /* Node Helpers */
  1542. func applyNodeCostPerCPUHr(nodeMap map[nodeKey]*nodePricing, resNodeCostPerCPUHr []*source.NodeCPUPricePerHrResult) {
  1543. for _, res := range resNodeCostPerCPUHr {
  1544. cluster := res.Cluster
  1545. if cluster == "" {
  1546. cluster = coreenv.GetClusterID()
  1547. }
  1548. node := res.Node
  1549. if node == "" {
  1550. log.Warnf("CostModel.ComputeAllocation: Node CPU cost query result missing field: node for node \"%s\"", node)
  1551. continue
  1552. }
  1553. instanceType := res.InstanceType
  1554. if instanceType == "" {
  1555. log.Warnf("CostModel.ComputeAllocation: Node CPU cost query result missing field: instance_type for node \"%s\"", node)
  1556. }
  1557. providerID := res.ProviderID
  1558. if providerID == "" {
  1559. log.Warnf("CostModel.ComputeAllocation: Node CPU cost query result missing field: provider_id for node \"%s\"", node)
  1560. }
  1561. key := newNodeKey(cluster, node)
  1562. if _, ok := nodeMap[key]; !ok {
  1563. nodeMap[key] = &nodePricing{
  1564. Name: node,
  1565. NodeType: instanceType,
  1566. ProviderID: provider.ParseID(providerID),
  1567. }
  1568. }
  1569. nodeMap[key].CostPerCPUHr = res.Data[0].Value
  1570. }
  1571. }
  1572. func applyNodeCostPerRAMGiBHr(nodeMap map[nodeKey]*nodePricing, resNodeCostPerRAMGiBHr []*source.NodeRAMPricePerGiBHrResult) {
  1573. for _, res := range resNodeCostPerRAMGiBHr {
  1574. cluster := res.Cluster
  1575. if cluster == "" {
  1576. cluster = coreenv.GetClusterID()
  1577. }
  1578. node := res.Node
  1579. if node == "" {
  1580. log.Warnf("CostModel.ComputeAllocation: Node RAM cost query result missing field: node for node \"%s\"", node)
  1581. continue
  1582. }
  1583. instanceType := res.InstanceType
  1584. if instanceType == "" {
  1585. log.Warnf("CostModel.ComputeAllocation: Node RAM cost query result missing field: instance_type for node \"%s\"", node)
  1586. }
  1587. providerID := res.ProviderID
  1588. if providerID == "" {
  1589. log.Warnf("CostModel.ComputeAllocation: Node RAM cost query result missing field: provider_id for node \"%s\"", node)
  1590. }
  1591. key := newNodeKey(cluster, node)
  1592. if _, ok := nodeMap[key]; !ok {
  1593. nodeMap[key] = &nodePricing{
  1594. Name: node,
  1595. NodeType: instanceType,
  1596. ProviderID: provider.ParseID(providerID),
  1597. }
  1598. }
  1599. nodeMap[key].CostPerRAMGiBHr = res.Data[0].Value
  1600. }
  1601. }
  1602. func applyNodeCostPerGPUHr(nodeMap map[nodeKey]*nodePricing, resNodeCostPerGPUHr []*source.NodeGPUPricePerHrResult) {
  1603. for _, res := range resNodeCostPerGPUHr {
  1604. cluster := res.Cluster
  1605. if cluster == "" {
  1606. cluster = coreenv.GetClusterID()
  1607. }
  1608. node := res.Node
  1609. if node == "" {
  1610. log.Warnf("CostModel.ComputeAllocation: Node GPU cost query result missing field: node for node \"%s\"", node)
  1611. continue
  1612. }
  1613. instanceType := res.InstanceType
  1614. if instanceType == "" {
  1615. log.Warnf("CostModel.ComputeAllocation: Node GPU cost query result missing field: instance_type for node \"%s\"", node)
  1616. }
  1617. providerID := res.ProviderID
  1618. if providerID == "" {
  1619. log.Warnf("CostModel.ComputeAllocation: Node GPU cost query result missing field: provider_id for node \"%s\"", node)
  1620. }
  1621. key := newNodeKey(cluster, node)
  1622. if _, ok := nodeMap[key]; !ok {
  1623. nodeMap[key] = &nodePricing{
  1624. Name: node,
  1625. NodeType: instanceType,
  1626. ProviderID: provider.ParseID(providerID),
  1627. }
  1628. }
  1629. nodeMap[key].CostPerGPUHr = res.Data[0].Value
  1630. }
  1631. }
  1632. func applyNodeSpot(nodeMap map[nodeKey]*nodePricing, resNodeIsSpot []*source.NodeIsSpotResult) {
  1633. for _, res := range resNodeIsSpot {
  1634. cluster := res.Cluster
  1635. if cluster == "" {
  1636. cluster = coreenv.GetClusterID()
  1637. }
  1638. node := res.Node
  1639. if node == "" {
  1640. log.Warnf("CostModel.ComputeAllocation: Node spot query result missing field: 'node'")
  1641. continue
  1642. }
  1643. key := newNodeKey(cluster, node)
  1644. if _, ok := nodeMap[key]; !ok {
  1645. log.Warnf("CostModel.ComputeAllocation: Node spot query result for missing node: %s", key)
  1646. continue
  1647. }
  1648. nodeMap[key].Preemptible = res.Data[0].Value > 0
  1649. }
  1650. }
  1651. func applyNodeDiscount(nodeMap map[nodeKey]*nodePricing, cm *CostModel) {
  1652. if cm == nil {
  1653. return
  1654. }
  1655. c, err := cm.Provider.GetConfig()
  1656. if err != nil {
  1657. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  1658. return
  1659. }
  1660. discount, err := ParsePercentString(c.Discount)
  1661. if err != nil {
  1662. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  1663. return
  1664. }
  1665. negotiatedDiscount, err := ParsePercentString(c.NegotiatedDiscount)
  1666. if err != nil {
  1667. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  1668. return
  1669. }
  1670. for _, node := range nodeMap {
  1671. // TODO GKE Reserved Instances into account
  1672. node.Discount = cm.Provider.CombinedDiscountForNode(node.NodeType, node.Preemptible, discount, negotiatedDiscount)
  1673. node.CostPerCPUHr *= (1.0 - node.Discount)
  1674. node.CostPerRAMGiBHr *= (1.0 - node.Discount)
  1675. }
  1676. }
  1677. func (cm *CostModel) applyNodesToPod(podMap map[podKey]*pod, nodeMap map[nodeKey]*nodePricing) {
  1678. for _, pod := range podMap {
  1679. for _, alloc := range pod.Allocations {
  1680. cluster := alloc.Properties.Cluster
  1681. nodeName := alloc.Properties.Node
  1682. thisNodeKey := newNodeKey(cluster, nodeName)
  1683. node := cm.getNodePricing(nodeMap, thisNodeKey)
  1684. alloc.Properties.ProviderID = node.ProviderID
  1685. alloc.CPUCost = alloc.CPUCoreHours * node.CostPerCPUHr
  1686. alloc.RAMCost = (alloc.RAMByteHours / 1024 / 1024 / 1024) * node.CostPerRAMGiBHr
  1687. alloc.GPUCost = alloc.GPUHours * node.CostPerGPUHr
  1688. }
  1689. }
  1690. }
  1691. // getCustomNodePricing converts the CostModel's configured custom pricing
  1692. // values into a nodePricing instance.
  1693. func (cm *CostModel) getCustomNodePricing(spot bool, providerID string) *nodePricing {
  1694. customPricingConfig, err := cm.Provider.GetConfig()
  1695. if err != nil {
  1696. return nil
  1697. }
  1698. cpuCostStr := customPricingConfig.CPU
  1699. gpuCostStr := customPricingConfig.GPU
  1700. ramCostStr := customPricingConfig.RAM
  1701. if spot {
  1702. cpuCostStr = customPricingConfig.SpotCPU
  1703. gpuCostStr = customPricingConfig.SpotGPU
  1704. ramCostStr = customPricingConfig.SpotRAM
  1705. }
  1706. node := &nodePricing{
  1707. Source: "custom",
  1708. ProviderID: providerID,
  1709. }
  1710. costPerCPUHr, err := strconv.ParseFloat(cpuCostStr, 64)
  1711. if err != nil {
  1712. log.Warnf("CostModel: custom pricing has illegal CPU cost: %s", cpuCostStr)
  1713. }
  1714. node.CostPerCPUHr = costPerCPUHr
  1715. costPerGPUHr, err := strconv.ParseFloat(gpuCostStr, 64)
  1716. if err != nil {
  1717. log.Warnf("CostModel: custom pricing has illegal GPU cost: %s", gpuCostStr)
  1718. }
  1719. node.CostPerGPUHr = costPerGPUHr
  1720. costPerRAMHr, err := strconv.ParseFloat(ramCostStr, 64)
  1721. if err != nil {
  1722. log.Warnf("CostModel: custom pricing has illegal RAM cost: %s", ramCostStr)
  1723. }
  1724. node.CostPerRAMGiBHr = costPerRAMHr
  1725. return node
  1726. }
  1727. // getNodePricing determines node pricing, given a key and a mapping from keys
  1728. // to their nodePricing instances, as well as the custom pricing configuration
  1729. // inherent to the CostModel instance. If custom pricing is set, use that. If
  1730. // not, use the pricing defined by the given key. If that doesn't exist, fall
  1731. // back on custom pricing as a default.
  1732. func (cm *CostModel) getNodePricing(nodeMap map[nodeKey]*nodePricing, nodeKey nodeKey) *nodePricing {
  1733. // Find the relevant nodePricing, if it exists. If not, substitute the
  1734. // custom nodePricing as a default.
  1735. node, ok := nodeMap[nodeKey]
  1736. if !ok || node == nil {
  1737. if nodeKey.Node != "" {
  1738. log.DedupedWarningf(5, "CostModel: failed to find node for %s", nodeKey)
  1739. }
  1740. // since the node pricing data is not found, and this won't change for the duration of the allocation
  1741. // build process, we can update the node map with the defaults to prevent future failed lookups
  1742. nodeMap[nodeKey] = cm.getCustomNodePricing(false, "")
  1743. return nodeMap[nodeKey]
  1744. }
  1745. // If custom pricing is enabled and can be retrieved, override detected
  1746. // node pricing with the custom values.
  1747. customPricingConfig, err := cm.Provider.GetConfig()
  1748. if err != nil {
  1749. log.Warnf("CostModel: failed to load custom pricing: %s", err)
  1750. }
  1751. if provider.CustomPricesEnabled(cm.Provider) && customPricingConfig != nil {
  1752. return cm.getCustomNodePricing(node.Preemptible, node.ProviderID)
  1753. }
  1754. node.Source = "prometheus"
  1755. // If any of the values are NaN or zero, replace them with the custom
  1756. // values as default.
  1757. // TODO:CLEANUP can't we parse these custom prices once? why do we store
  1758. // them as strings like this?
  1759. if node.CostPerCPUHr == 0 || math.IsNaN(node.CostPerCPUHr) {
  1760. cpuCostStr := customPricingConfig.CPU
  1761. if node.Preemptible {
  1762. cpuCostStr = customPricingConfig.SpotCPU
  1763. }
  1764. log.Warnf("CostModel: node pricing has illegal CostPerCPUHr; replacing with custom pricing: %s %s", nodeKey, cpuCostStr)
  1765. costPerCPUHr, err := strconv.ParseFloat(cpuCostStr, 64)
  1766. if err != nil {
  1767. log.Warnf("CostModel: custom pricing has illegal CPU cost: %s", cpuCostStr)
  1768. }
  1769. node.CostPerCPUHr = costPerCPUHr
  1770. node.Source += "/customCPU"
  1771. }
  1772. if math.IsNaN(node.CostPerGPUHr) {
  1773. gpuCostStr := customPricingConfig.GPU
  1774. if node.Preemptible {
  1775. gpuCostStr = customPricingConfig.SpotGPU
  1776. }
  1777. log.Warnf("CostModel: node pricing has illegal CostPerGPUHr; replacing with custom pricing: %s %s", nodeKey, gpuCostStr)
  1778. costPerGPUHr, err := strconv.ParseFloat(gpuCostStr, 64)
  1779. if err != nil {
  1780. log.Warnf("CostModel: custom pricing has illegal GPU cost: %s", gpuCostStr)
  1781. }
  1782. node.CostPerGPUHr = costPerGPUHr
  1783. node.Source += "/customGPU"
  1784. }
  1785. if node.CostPerRAMGiBHr == 0 || math.IsNaN(node.CostPerRAMGiBHr) {
  1786. ramCostStr := customPricingConfig.RAM
  1787. if node.Preemptible {
  1788. ramCostStr = customPricingConfig.SpotRAM
  1789. }
  1790. log.Warnf("CostModel: node pricing has illegal CostPerRAMHr; replacing with custom pricing: %s %s", nodeKey, ramCostStr)
  1791. costPerRAMHr, err := strconv.ParseFloat(ramCostStr, 64)
  1792. if err != nil {
  1793. log.Warnf("CostModel: custom pricing has illegal RAM cost: %s", ramCostStr)
  1794. }
  1795. node.CostPerRAMGiBHr = costPerRAMHr
  1796. node.Source += "/customRAM"
  1797. }
  1798. // Double check each for NaNs, as there is a chance that our custom pricing
  1799. // config could, itself, contain NaNs...
  1800. if math.IsNaN(node.CostPerCPUHr) || math.IsInf(node.CostPerCPUHr, 0) {
  1801. log.Warnf("CostModel: %s: node pricing has illegal CPU value: %v (setting to 0.0)", nodeKey, node.CostPerCPUHr)
  1802. node.CostPerCPUHr = 0.0
  1803. }
  1804. if math.IsNaN(node.CostPerGPUHr) || math.IsInf(node.CostPerGPUHr, 0) {
  1805. log.Warnf("CostModel: %s: node pricing has illegal RAM value: %v (setting to 0.0)", nodeKey, node.CostPerGPUHr)
  1806. node.CostPerGPUHr = 0.0
  1807. }
  1808. if math.IsNaN(node.CostPerRAMGiBHr) || math.IsInf(node.CostPerRAMGiBHr, 0) {
  1809. log.Warnf("CostModel: %s: node pricing has illegal RAM value: %v (setting to 0.0)", nodeKey, node.CostPerRAMGiBHr)
  1810. node.CostPerRAMGiBHr = 0.0
  1811. }
  1812. return node
  1813. }
  1814. /* PV/PVC Helpers */
  1815. func buildPVMap(
  1816. resolution time.Duration,
  1817. pvMap map[pvKey]*pv,
  1818. resPVCostPerGiBHour []*source.PVPricePerGiBHourResult,
  1819. resPVActiveMins []*source.PVActiveMinutesResult,
  1820. resPVMeta []*source.PVInfoResult,
  1821. window opencost.Window,
  1822. ) {
  1823. for _, result := range resPVActiveMins {
  1824. key, err := newResultPVKey(result.Cluster, result.PersistentVolume)
  1825. if err != nil {
  1826. log.Warnf("CostModel.ComputeAllocation: pv bytes query result missing field: %s", err)
  1827. continue
  1828. }
  1829. pvStart, pvEnd := calculateStartAndEnd(result.Data, resolution, window)
  1830. if pvStart.IsZero() || pvEnd.IsZero() {
  1831. log.Warnf("CostModel.ComputeAllocation: pv %s has no running time", key)
  1832. }
  1833. pvMap[key] = &pv{
  1834. Cluster: key.Cluster,
  1835. Name: key.PersistentVolume,
  1836. Start: pvStart,
  1837. End: pvEnd,
  1838. }
  1839. }
  1840. for _, result := range resPVCostPerGiBHour {
  1841. key, err := newResultPVKey(result.Cluster, result.VolumeName)
  1842. if err != nil {
  1843. log.Warnf("CostModel.ComputeAllocation: thisPV bytes query result missing field: %s", err)
  1844. continue
  1845. }
  1846. if _, ok := pvMap[key]; !ok {
  1847. pvMap[key] = &pv{
  1848. Cluster: key.Cluster,
  1849. Name: key.PersistentVolume,
  1850. }
  1851. }
  1852. pvMap[key].CostPerGiBHour = result.Data[0].Value
  1853. }
  1854. for _, result := range resPVMeta {
  1855. key, err := newResultPVKey(result.Cluster, result.PersistentVolume)
  1856. if err != nil {
  1857. log.Warnf("error getting key for PV: %v", err)
  1858. continue
  1859. }
  1860. // only add metadata for disks that exist in the other metrics
  1861. if _, ok := pvMap[key]; ok {
  1862. provId := result.ProviderID
  1863. if provId == "" {
  1864. log.Warnf("error getting provider id for PV %v: %v", key, err)
  1865. continue
  1866. }
  1867. pvMap[key].ProviderID = provId
  1868. }
  1869. }
  1870. }
  1871. func applyPVBytes(pvMap map[pvKey]*pv, resPVBytes []*source.PVBytesResult) {
  1872. for _, res := range resPVBytes {
  1873. key, err := newResultPVKey(res.Cluster, res.PersistentVolume)
  1874. if err != nil {
  1875. log.Warnf("CostModel.ComputeAllocation: pv bytes query result missing field: %s", err)
  1876. continue
  1877. }
  1878. if _, ok := pvMap[key]; !ok {
  1879. log.Warnf("CostModel.ComputeAllocation: pv bytes result for missing pv: %s", key)
  1880. continue
  1881. }
  1882. pvBytesUsed := res.Data[0].Value
  1883. if pvBytesUsed < PV_USAGE_SANITY_LIMIT_BYTES {
  1884. pvMap[key].Bytes = pvBytesUsed
  1885. } else {
  1886. pvMap[key].Bytes = 0
  1887. log.Warnf("PV usage exceeds sanity limit, clamping to zero")
  1888. }
  1889. }
  1890. }
  1891. func buildPVCMap(resolution time.Duration, pvcMap map[pvcKey]*pvc, pvMap map[pvKey]*pv, resPVCInfo []*source.PVCInfoResult, window opencost.Window) {
  1892. for _, res := range resPVCInfo {
  1893. cluster := res.Cluster
  1894. if cluster == "" {
  1895. cluster = coreenv.GetClusterID()
  1896. }
  1897. namespace := res.Namespace
  1898. name := res.PersistentVolumeClaim
  1899. volume := res.VolumeName
  1900. storageClass := res.StorageClass
  1901. if namespace == "" || name == "" || volume == "" || storageClass == "" {
  1902. log.DedupedWarningf(10, "CostModel.ComputeAllocation: pvc info query result missing field")
  1903. continue
  1904. }
  1905. pvKey := newPVKey(cluster, volume)
  1906. pvcKey := newPVCKey(cluster, namespace, name)
  1907. pvcStart, pvcEnd := calculateStartAndEnd(res.Data, resolution, window)
  1908. if pvcStart.IsZero() || pvcEnd.IsZero() {
  1909. log.Warnf("CostModel.ComputeAllocation: pvc %s has no running time", pvcKey)
  1910. }
  1911. if _, ok := pvMap[pvKey]; !ok {
  1912. continue
  1913. }
  1914. pvMap[pvKey].StorageClass = storageClass
  1915. if _, ok := pvcMap[pvcKey]; !ok {
  1916. pvcMap[pvcKey] = &pvc{}
  1917. }
  1918. pvcMap[pvcKey].Name = name
  1919. pvcMap[pvcKey].Namespace = namespace
  1920. pvcMap[pvcKey].Cluster = cluster
  1921. pvcMap[pvcKey].Volume = pvMap[pvKey]
  1922. pvcMap[pvcKey].Start = pvcStart
  1923. pvcMap[pvcKey].End = pvcEnd
  1924. }
  1925. }
  1926. func applyPVCBytesRequested(pvcMap map[pvcKey]*pvc, resPVCBytesRequested []*source.PVCBytesRequestedResult) {
  1927. for _, res := range resPVCBytesRequested {
  1928. key, err := newResultPVCKey(res.Cluster, res.Namespace, res.PersistentVolumeClaim)
  1929. if err != nil {
  1930. continue
  1931. }
  1932. if _, ok := pvcMap[key]; !ok {
  1933. continue
  1934. }
  1935. pvcMap[key].Bytes = res.Data[0].Value
  1936. }
  1937. }
  1938. func buildPodPVCMap(podPVCMap map[podKey][]*pvc, pvMap map[pvKey]*pv, pvcMap map[pvcKey]*pvc, podMap map[podKey]*pod, resPodPVCAllocation []*source.PodPVCAllocationResult, podUIDKeyMap map[podKey][]podKey, ingestPodUID bool) {
  1939. for _, res := range resPodPVCAllocation {
  1940. cluster := res.Cluster
  1941. if cluster == "" {
  1942. cluster = coreenv.GetClusterID()
  1943. }
  1944. namespace := res.Namespace
  1945. pod := res.Pod
  1946. name := res.PersistentVolumeClaim
  1947. volume := res.PersistentVolume
  1948. if namespace == "" || pod == "" || name == "" || volume == "" {
  1949. log.DedupedWarningf(5, "CostModel.ComputeAllocation: pvc allocation query result missing field")
  1950. continue
  1951. }
  1952. key := newPodKey(cluster, namespace, pod)
  1953. pvKey := newPVKey(cluster, volume)
  1954. pvcKey := newPVCKey(cluster, namespace, name)
  1955. var keys []podKey
  1956. if ingestPodUID {
  1957. if uidKeys, ok := podUIDKeyMap[key]; ok {
  1958. keys = append(keys, uidKeys...)
  1959. }
  1960. } else {
  1961. keys = []podKey{key}
  1962. }
  1963. for _, key := range keys {
  1964. if _, ok := pvMap[pvKey]; !ok {
  1965. log.DedupedWarningf(5, "CostModel.ComputeAllocation: pv missing for pvc allocation query result: %s", pvKey)
  1966. continue
  1967. }
  1968. if _, ok := podPVCMap[key]; !ok {
  1969. podPVCMap[key] = []*pvc{}
  1970. }
  1971. pvc, ok := pvcMap[pvcKey]
  1972. if !ok {
  1973. log.DedupedWarningf(5, "CostModel.ComputeAllocation: pvc missing for pvc allocation query: %s", pvcKey)
  1974. continue
  1975. }
  1976. if pod, ok := podMap[key]; !ok || len(pod.Allocations) <= 0 {
  1977. log.DedupedWarningf(10, "CostModel.ComputeAllocation: pvc %s for missing pod %s", pvcKey, key)
  1978. continue
  1979. }
  1980. pvc.Mounted = true
  1981. podPVCMap[key] = append(podPVCMap[key], pvc)
  1982. }
  1983. }
  1984. }
  1985. func applyPVCsToPods(window opencost.Window, podMap map[podKey]*pod, podPVCMap map[podKey][]*pvc, pvcMap map[pvcKey]*pvc) {
  1986. // Because PVCs can be shared among pods, the respective pv cost
  1987. // needs to be evenly distributed to those pods based on time
  1988. // running, as well as the amount of time the pvc was shared.
  1989. // Build a relation between every pvc to the pods that mount it
  1990. // and a window representing the interval during which they
  1991. // were associated.
  1992. pvcPodWindowMap := make(map[pvcKey]map[podKey]opencost.Window)
  1993. for thisPodKey, thisPod := range podMap {
  1994. if pvcs, ok := podPVCMap[thisPodKey]; ok {
  1995. for _, thisPVC := range pvcs {
  1996. // Determine the (start, end) of the relationship between the
  1997. // given pvc and the associated Allocation so that a precise
  1998. // number of hours can be used to compute cumulative cost.
  1999. s, e := thisPod.Start, thisPod.End
  2000. if thisPVC.Start.After(thisPod.Start) {
  2001. s = thisPVC.Start
  2002. }
  2003. if thisPVC.End.Before(thisPod.End) {
  2004. e = thisPVC.End
  2005. }
  2006. thisPVCKey := thisPVC.key()
  2007. if pvcPodWindowMap[thisPVCKey] == nil {
  2008. pvcPodWindowMap[thisPVCKey] = make(map[podKey]opencost.Window)
  2009. }
  2010. pvcPodWindowMap[thisPVCKey][thisPodKey] = opencost.NewWindow(&s, &e)
  2011. }
  2012. }
  2013. }
  2014. for thisPVCKey, podWindowMap := range pvcPodWindowMap {
  2015. // Build out a pv price coefficient for each pod with a pvc. Each
  2016. // pvc-pod relation needs a coefficient which modifies the pv cost
  2017. // such that pv costs can be shared between all pods using that pvc.
  2018. // Get single-point intervals from alloc-pvc relation windows.
  2019. intervals := getIntervalPointsFromWindows(podWindowMap)
  2020. pvc, ok := pvcMap[thisPVCKey]
  2021. if !ok {
  2022. log.Warnf("Allocation: Compute: applyPVCsToPods: missing pvc with key %s", thisPVCKey)
  2023. continue
  2024. }
  2025. if pvc == nil {
  2026. log.Warnf("Allocation: Compute: applyPVCsToPods: nil pvc with key %s", thisPVCKey)
  2027. continue
  2028. }
  2029. // Determine coefficients for each pvc-pod relation.
  2030. sharedPVCCostCoefficients, err := getPVCCostCoefficients(intervals, pvc)
  2031. if err != nil {
  2032. log.Warnf("Allocation: Compute: applyPVCsToPods: getPVCCostCoefficients: %s", err)
  2033. continue
  2034. }
  2035. // Distribute pvc costs to Allocations
  2036. for thisPodKey, coeffComponents := range sharedPVCCostCoefficients {
  2037. pod, ok2 := podMap[thisPodKey]
  2038. // If pod does not exist or the pod does not have any allocations
  2039. // get unmounted pod for cluster
  2040. if !ok2 || len(pod.Allocations) == 0 {
  2041. // Get namespace unmounted pod, as pvc will have a namespace
  2042. pod = getUnmountedPodForNamespace(window, podMap, pvc.Cluster, pvc.Namespace)
  2043. }
  2044. for _, alloc := range pod.Allocations {
  2045. s, e := pod.Start, pod.End
  2046. minutes := e.Sub(s).Minutes()
  2047. hrs := minutes / 60.0
  2048. gib := pvc.Bytes / 1024 / 1024 / 1024
  2049. cost := pvc.Volume.CostPerGiBHour * gib * hrs
  2050. byteHours := pvc.Bytes * hrs
  2051. coef := getCoefficientFromComponents(coeffComponents)
  2052. // Apply the size and cost of the pv to the allocation, each
  2053. // weighted by count (i.e. the number of containers in the pod)
  2054. // record the amount of total PVBytes Hours attributable to a given pv
  2055. if alloc.PVs == nil {
  2056. alloc.PVs = opencost.PVAllocations{}
  2057. }
  2058. pvKey := opencost.PVKey{
  2059. Cluster: pvc.Volume.Cluster,
  2060. Name: pvc.Volume.Name,
  2061. }
  2062. // Both Cost and byteHours should be multiplied by the coef and divided by count
  2063. // so that if all allocations with a given pv key are summed the result of those
  2064. // would be equal to the values of the original pv
  2065. count := float64(len(pod.Allocations))
  2066. alloc.PVs[pvKey] = &opencost.PVAllocation{
  2067. ByteHours: byteHours * coef / count,
  2068. Cost: cost * coef / count,
  2069. ProviderID: pvc.Volume.ProviderID,
  2070. }
  2071. }
  2072. }
  2073. }
  2074. }
  2075. func applyUnmountedPVs(window opencost.Window, podMap map[podKey]*pod, pvMap map[pvKey]*pv, pvcMap map[pvcKey]*pvc) {
  2076. for _, pv := range pvMap {
  2077. mounted := false
  2078. for _, pvc := range pvcMap {
  2079. if pvc.Volume == nil {
  2080. continue
  2081. }
  2082. if pvc.Volume == pv {
  2083. mounted = true
  2084. break
  2085. }
  2086. }
  2087. if !mounted {
  2088. // a pv without a pvc will not have a namespace, so get the cluster unmounted pod
  2089. pod := getUnmountedPodForCluster(window, podMap, pv.Cluster)
  2090. // Calculate pv Cost
  2091. // Unmounted pv should have correct keyso it can still reconcile
  2092. thisPVKey := opencost.PVKey{
  2093. Cluster: pv.Cluster,
  2094. Name: pv.Name,
  2095. }
  2096. gib := pv.Bytes / 1024 / 1024 / 1024
  2097. hrs := pv.minutes() / 60.0
  2098. cost := pv.CostPerGiBHour * gib * hrs
  2099. unmountedPVs := opencost.PVAllocations{
  2100. thisPVKey: {
  2101. ByteHours: pv.Bytes * hrs,
  2102. Cost: cost,
  2103. },
  2104. }
  2105. pod.Allocations[opencost.UnmountedSuffix].PVs = pod.Allocations[opencost.UnmountedSuffix].PVs.Add(unmountedPVs)
  2106. }
  2107. }
  2108. }
  2109. func applyUnmountedPVCs(window opencost.Window, podMap map[podKey]*pod, pvcMap map[pvcKey]*pvc) {
  2110. for _, pvc := range pvcMap {
  2111. if !pvc.Mounted && pvc.Volume != nil {
  2112. // Get namespace unmounted pod, as pvc will have a namespace
  2113. pod := getUnmountedPodForNamespace(window, podMap, pvc.Cluster, pvc.Namespace)
  2114. // Calculate pv Cost
  2115. // Unmounted pv should have correct key so it can still reconcile
  2116. thisPVKey := opencost.PVKey{
  2117. Cluster: pvc.Volume.Cluster,
  2118. Name: pvc.Volume.Name,
  2119. }
  2120. // Use the Volume Bytes here because pvc bytes could be different,
  2121. // however the pv bytes are what are going to determine cost
  2122. gib := pvc.Volume.Bytes / 1024 / 1024 / 1024
  2123. hrs := pvc.Volume.minutes() / 60.0
  2124. cost := pvc.Volume.CostPerGiBHour * gib * hrs
  2125. unmountedPVs := opencost.PVAllocations{
  2126. thisPVKey: {
  2127. ByteHours: pvc.Volume.Bytes * hrs,
  2128. Cost: cost,
  2129. },
  2130. }
  2131. pod.Allocations[opencost.UnmountedSuffix].PVs = pod.Allocations[opencost.UnmountedSuffix].PVs.Add(unmountedPVs)
  2132. }
  2133. }
  2134. }
  2135. /* Helper Helpers */
  2136. // getUnmountedPodForCluster retrieve the unmounted pod for a cluster and create it if it does not exist
  2137. func getUnmountedPodForCluster(window opencost.Window, podMap map[podKey]*pod, cluster string) *pod {
  2138. container := opencost.UnmountedSuffix
  2139. podName := opencost.UnmountedSuffix
  2140. namespace := opencost.UnmountedSuffix
  2141. node := ""
  2142. thisPodKey := getUnmountedPodKey(cluster)
  2143. // Initialize pod and container if they do not already exist
  2144. thisPod, ok := podMap[thisPodKey]
  2145. if !ok {
  2146. thisPod = &pod{
  2147. Window: window.Clone(),
  2148. Start: *window.Start(),
  2149. End: *window.End(),
  2150. Key: thisPodKey,
  2151. Allocations: map[string]*opencost.Allocation{},
  2152. }
  2153. thisPod.appendContainer(container)
  2154. thisPod.Allocations[container].Properties.Cluster = cluster
  2155. thisPod.Allocations[container].Properties.Node = node
  2156. thisPod.Allocations[container].Properties.Namespace = namespace
  2157. thisPod.Allocations[container].Properties.Pod = podName
  2158. thisPod.Allocations[container].Properties.Container = container
  2159. thisPod.Node = node
  2160. podMap[thisPodKey] = thisPod
  2161. }
  2162. return thisPod
  2163. }
  2164. // getUnmountedPodForNamespace is as getUnmountedPodForCluster, but keys allocation property pod/namespace field off namespace
  2165. // This creates or adds allocations to an unmounted pod in the specified namespace, rather than in __unmounted__
  2166. func getUnmountedPodForNamespace(window opencost.Window, podMap map[podKey]*pod, cluster string, namespace string) *pod {
  2167. container := opencost.UnmountedSuffix
  2168. podName := fmt.Sprintf("%s-unmounted-pvcs", namespace)
  2169. node := ""
  2170. thisPodKey := newPodKey(cluster, namespace, podName)
  2171. // Initialize pod and container if they do not already exist
  2172. thisPod, ok := podMap[thisPodKey]
  2173. if !ok {
  2174. thisPod = &pod{
  2175. Window: window.Clone(),
  2176. Start: *window.Start(),
  2177. End: *window.End(),
  2178. Key: thisPodKey,
  2179. Allocations: map[string]*opencost.Allocation{},
  2180. }
  2181. thisPod.appendContainer(container)
  2182. thisPod.Allocations[container].Properties.Cluster = cluster
  2183. thisPod.Allocations[container].Properties.Node = node
  2184. thisPod.Allocations[container].Properties.Namespace = namespace
  2185. thisPod.Allocations[container].Properties.Pod = podName
  2186. thisPod.Allocations[container].Properties.Container = container
  2187. thisPod.Node = node
  2188. podMap[thisPodKey] = thisPod
  2189. }
  2190. return thisPod
  2191. }
  2192. func calculateStartAndEnd(result []*util.Vector, resolution time.Duration, window opencost.Window) (time.Time, time.Time) {
  2193. // Start and end for a range vector are pulled from the timestamps of the
  2194. // first and final values in the range. There is no "offsetting" required
  2195. // of the start or the end, as we used to do. If you query for a duration
  2196. // of time that is divisible by the given resolution, and set the end time
  2197. // to be precisely the end of the window, Prometheus should give all the
  2198. // relevant timestamps.
  2199. //
  2200. // E.g. avg(kube_pod_container_status_running{}) by (pod, namespace)[1h:1m]
  2201. // with time=01:00:00 will return, for a pod running the entire time,
  2202. // 61 timestamps where the first is 00:00:00 and the last is 01:00:00.
  2203. s := time.Unix(int64(result[0].Timestamp), 0).UTC()
  2204. e := time.Unix(int64(result[len(result)-1].Timestamp), 0).UTC()
  2205. // The only corner-case here is what to do if you only get one timestamp.
  2206. // This dilemma still requires the use of the resolution, and can be
  2207. // clamped using the window. In this case, we want to honor the existence
  2208. // of the pod by giving "one resolution" worth of duration, half on each
  2209. // side of the given timestamp.
  2210. if s.Equal(e) {
  2211. s = s.Add(-1 * resolution / time.Duration(2))
  2212. e = e.Add(resolution / time.Duration(2))
  2213. }
  2214. if s.Before(*window.Start()) {
  2215. s = *window.Start()
  2216. }
  2217. if e.After(*window.End()) {
  2218. e = *window.End()
  2219. }
  2220. // prevent end times in the future
  2221. now := time.Now().UTC()
  2222. if e.After(now) {
  2223. e = now
  2224. }
  2225. return s, e
  2226. }
  2227. func getSanitizedDeviceName(deviceName string) string {
  2228. if strings.Contains(deviceName, "nvidia") {
  2229. return "nvidia"
  2230. }
  2231. return deviceName
  2232. }