allocation_helpers.go 69 KB

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