allocation_helpers.go 78 KB

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