2
0

allocation_helpers.go 77 KB

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