allocation_helpers.go 74 KB

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