allocation_helpers.go 74 KB

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