allocation_helpers.go 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326
  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 applyGPUUsageAvg(podMap map[podKey]*pod, resGPUUsageAvg []*prom.QueryResult, podUIDKeyMap map[podKey][]podKey) {
  528. // Example PromQueryResult: {container="dcgmproftester12", namespace="gpu", pod="dcgmproftester3-deployment-fc89c8dd6-ph7z5"} 0.997307
  529. for _, res := range resGPUUsageAvg {
  530. key, err := resultPodKey(res, env.GetPromClusterLabel(), "namespace")
  531. if err != nil {
  532. log.DedupedWarningf(10, "CostModel.ComputeAllocation: GPU usage avg result missing field: %s", err)
  533. continue
  534. }
  535. var pods []*pod
  536. if thisPod, ok := podMap[key]; !ok {
  537. if uidKeys, ok := podUIDKeyMap[key]; ok {
  538. for _, uidKey := range uidKeys {
  539. thisPod, ok = podMap[uidKey]
  540. if ok {
  541. pods = append(pods, thisPod)
  542. }
  543. }
  544. } else {
  545. continue
  546. }
  547. } else {
  548. pods = []*pod{thisPod}
  549. }
  550. for _, thisPod := range pods {
  551. container, err := res.GetString("container")
  552. if err != nil {
  553. log.DedupedWarningf(10, "CostModel.ComputeAllocation: GPU usage avg query result missing 'container': %s", key)
  554. continue
  555. }
  556. if _, ok := thisPod.Allocations[container]; !ok {
  557. thisPod.appendContainer(container)
  558. }
  559. // DCGM_FI_PROF_GR_ENGINE_ACTIVE metric is a float between 0-1.
  560. thisPod.Allocations[container].GPUUsageAverage = res.Values[0].Value
  561. }
  562. }
  563. }
  564. func applyGPUsAllocated(podMap map[podKey]*pod, resGPUsRequested []*prom.QueryResult, resGPUsAllocated []*prom.QueryResult, podUIDKeyMap map[podKey][]podKey) {
  565. if len(resGPUsAllocated) > 0 { // Use the new query, when it's become available in a window
  566. resGPUsRequested = resGPUsAllocated
  567. }
  568. for _, res := range resGPUsRequested {
  569. key, err := resultPodKey(res, env.GetPromClusterLabel(), "namespace")
  570. if err != nil {
  571. log.DedupedWarningf(10, "CostModel.ComputeAllocation: GPU request result missing field: %s", err)
  572. continue
  573. }
  574. container, err := res.GetString("container")
  575. if err != nil {
  576. log.DedupedWarningf(10, "CostModel.ComputeAllocation: GPU request query result missing 'container': %s", key)
  577. continue
  578. }
  579. var pods []*pod
  580. if thisPod, ok := podMap[key]; !ok {
  581. if uidKeys, ok := podUIDKeyMap[key]; ok {
  582. for _, uidKey := range uidKeys {
  583. thisPod, ok = podMap[uidKey]
  584. if ok {
  585. pods = append(pods, thisPod)
  586. }
  587. }
  588. } else {
  589. continue
  590. }
  591. } else {
  592. pods = []*pod{thisPod}
  593. }
  594. for _, thisPod := range pods {
  595. if _, ok := thisPod.Allocations[container]; !ok {
  596. thisPod.appendContainer(container)
  597. }
  598. hrs := thisPod.Allocations[container].Minutes() / 60.0
  599. thisPod.Allocations[container].GPUHours = res.Values[0].Value * hrs
  600. // For now, it will always be the case that Request==Allocation. If
  601. // you would like to use a GPU you need to request the full GPU.
  602. // Therefore max(usage,request) will always equal request. In the
  603. // future this may need to be refactored when building support for
  604. // GPU Time Slicing.
  605. thisPod.Allocations[container].GPURequestAverage = res.Values[0].Value
  606. }
  607. }
  608. }
  609. func applyNetworkTotals(podMap map[podKey]*pod, resNetworkTransferBytes []*prom.QueryResult, resNetworkReceiveBytes []*prom.QueryResult, podUIDKeyMap map[podKey][]podKey) {
  610. for _, res := range resNetworkTransferBytes {
  611. podKey, err := resultPodKey(res, env.GetPromClusterLabel(), "namespace")
  612. if err != nil {
  613. log.DedupedWarningf(10, "CostModel.ComputeAllocation: Network Transfer Bytes query result missing field: %s", err)
  614. continue
  615. }
  616. var pods []*pod
  617. if thisPod, ok := podMap[podKey]; !ok {
  618. if uidKeys, ok := podUIDKeyMap[podKey]; ok {
  619. for _, uidKey := range uidKeys {
  620. thisPod, ok = podMap[uidKey]
  621. if ok {
  622. pods = append(pods, thisPod)
  623. }
  624. }
  625. } else {
  626. continue
  627. }
  628. } else {
  629. pods = []*pod{thisPod}
  630. }
  631. for _, thisPod := range pods {
  632. for _, alloc := range thisPod.Allocations {
  633. alloc.NetworkTransferBytes = res.Values[0].Value / float64(len(thisPod.Allocations)) / float64(len(pods))
  634. }
  635. }
  636. }
  637. for _, res := range resNetworkReceiveBytes {
  638. podKey, err := resultPodKey(res, env.GetPromClusterLabel(), "namespace")
  639. if err != nil {
  640. log.DedupedWarningf(10, "CostModel.ComputeAllocation: Network Receive Bytes query result missing field: %s", err)
  641. continue
  642. }
  643. var pods []*pod
  644. if thisPod, ok := podMap[podKey]; !ok {
  645. if uidKeys, ok := podUIDKeyMap[podKey]; ok {
  646. for _, uidKey := range uidKeys {
  647. thisPod, ok = podMap[uidKey]
  648. if ok {
  649. pods = append(pods, thisPod)
  650. }
  651. }
  652. } else {
  653. continue
  654. }
  655. } else {
  656. pods = []*pod{thisPod}
  657. }
  658. for _, thisPod := range pods {
  659. for _, alloc := range thisPod.Allocations {
  660. alloc.NetworkReceiveBytes = res.Values[0].Value / float64(len(thisPod.Allocations)) / float64(len(pods))
  661. }
  662. }
  663. }
  664. }
  665. func applyNetworkAllocation(podMap map[podKey]*pod, resNetworkGiB []*prom.QueryResult, resNetworkCostPerGiB []*prom.QueryResult, podUIDKeyMap map[podKey][]podKey, networkCostSubType string) {
  666. costPerGiBByCluster := map[string]float64{}
  667. for _, res := range resNetworkCostPerGiB {
  668. cluster, err := res.GetString(env.GetPromClusterLabel())
  669. if err != nil {
  670. cluster = env.GetClusterID()
  671. }
  672. costPerGiBByCluster[cluster] = res.Values[0].Value
  673. }
  674. for _, res := range resNetworkGiB {
  675. podKey, err := resultPodKey(res, env.GetPromClusterLabel(), "namespace")
  676. if err != nil {
  677. log.DedupedWarningf(10, "CostModel.ComputeAllocation: Network allocation query result missing field: %s", err)
  678. continue
  679. }
  680. var pods []*pod
  681. if thisPod, ok := podMap[podKey]; !ok {
  682. if uidKeys, ok := podUIDKeyMap[podKey]; ok {
  683. for _, uidKey := range uidKeys {
  684. thisPod, ok = podMap[uidKey]
  685. if ok {
  686. pods = append(pods, thisPod)
  687. }
  688. }
  689. } else {
  690. continue
  691. }
  692. } else {
  693. pods = []*pod{thisPod}
  694. }
  695. for _, thisPod := range pods {
  696. for _, alloc := range thisPod.Allocations {
  697. gib := res.Values[0].Value / float64(len(thisPod.Allocations))
  698. costPerGiB := costPerGiBByCluster[podKey.Cluster]
  699. currentNetworkSubCost := gib * costPerGiB / float64(len(pods))
  700. switch networkCostSubType {
  701. case networkCrossZoneCost:
  702. alloc.NetworkCrossZoneCost = currentNetworkSubCost
  703. case networkCrossRegionCost:
  704. alloc.NetworkCrossRegionCost = currentNetworkSubCost
  705. case networkInternetCost:
  706. alloc.NetworkInternetCost = currentNetworkSubCost
  707. default:
  708. log.Warnf("CostModel.applyNetworkAllocation: unknown network subtype passed to the function: %s", networkCostSubType)
  709. }
  710. alloc.NetworkCost += currentNetworkSubCost
  711. }
  712. }
  713. }
  714. }
  715. func resToNodeLabels(resNodeLabels []*prom.QueryResult) map[nodeKey]map[string]string {
  716. nodeLabels := map[nodeKey]map[string]string{}
  717. for _, res := range resNodeLabels {
  718. nodeKey, err := resultNodeKey(res, env.GetPromClusterLabel(), "node")
  719. if err != nil {
  720. continue
  721. }
  722. if _, ok := nodeLabels[nodeKey]; !ok {
  723. nodeLabels[nodeKey] = map[string]string{}
  724. }
  725. for _, rawK := range env.GetAllocationNodeLabelsIncludeList() {
  726. labels := res.GetLabels()
  727. // Sanitize the given label name to match Prometheus formatting
  728. // e.g. topology.kubernetes.io/zone => topology_kubernetes_io_zone
  729. k := promutil.SanitizeLabelName(rawK)
  730. if v, ok := labels[k]; ok {
  731. nodeLabels[nodeKey][k] = v
  732. continue
  733. }
  734. // Try with the "label_" prefix, if not found
  735. // e.g. topology_kubernetes_io_zone => label_topology_kubernetes_io_zone
  736. k = fmt.Sprintf("label_%s", k)
  737. if v, ok := labels[k]; ok {
  738. nodeLabels[nodeKey][k] = v
  739. }
  740. }
  741. }
  742. return nodeLabels
  743. }
  744. func resToNamespaceLabels(resNamespaceLabels []*prom.QueryResult) map[namespaceKey]map[string]string {
  745. namespaceLabels := map[namespaceKey]map[string]string{}
  746. for _, res := range resNamespaceLabels {
  747. nsKey, err := resultNamespaceKey(res, env.GetPromClusterLabel(), "namespace")
  748. if err != nil {
  749. continue
  750. }
  751. if _, ok := namespaceLabels[nsKey]; !ok {
  752. namespaceLabels[nsKey] = map[string]string{}
  753. }
  754. for k, l := range res.GetLabels() {
  755. namespaceLabels[nsKey][k] = l
  756. }
  757. }
  758. return namespaceLabels
  759. }
  760. func resToPodLabels(resPodLabels []*prom.QueryResult, podUIDKeyMap map[podKey][]podKey, ingestPodUID bool) map[podKey]map[string]string {
  761. podLabels := map[podKey]map[string]string{}
  762. for _, res := range resPodLabels {
  763. key, err := resultPodKey(res, env.GetPromClusterLabel(), "namespace")
  764. if err != nil {
  765. continue
  766. }
  767. var keys []podKey
  768. if ingestPodUID {
  769. if uidKeys, ok := podUIDKeyMap[key]; ok {
  770. keys = append(keys, uidKeys...)
  771. }
  772. } else {
  773. keys = []podKey{key}
  774. }
  775. for _, key := range keys {
  776. if _, ok := podLabels[key]; !ok {
  777. podLabels[key] = map[string]string{}
  778. }
  779. for k, l := range res.GetLabels() {
  780. podLabels[key][k] = l
  781. }
  782. }
  783. }
  784. return podLabels
  785. }
  786. func resToNamespaceAnnotations(resNamespaceAnnotations []*prom.QueryResult) map[string]map[string]string {
  787. namespaceAnnotations := map[string]map[string]string{}
  788. for _, res := range resNamespaceAnnotations {
  789. namespace, err := res.GetString("namespace")
  790. if err != nil {
  791. continue
  792. }
  793. if _, ok := namespaceAnnotations[namespace]; !ok {
  794. namespaceAnnotations[namespace] = map[string]string{}
  795. }
  796. for k, l := range res.GetAnnotations() {
  797. namespaceAnnotations[namespace][k] = l
  798. }
  799. }
  800. return namespaceAnnotations
  801. }
  802. func resToPodAnnotations(resPodAnnotations []*prom.QueryResult, podUIDKeyMap map[podKey][]podKey, ingestPodUID bool) map[podKey]map[string]string {
  803. podAnnotations := map[podKey]map[string]string{}
  804. for _, res := range resPodAnnotations {
  805. key, err := resultPodKey(res, env.GetPromClusterLabel(), "namespace")
  806. if err != nil {
  807. continue
  808. }
  809. var keys []podKey
  810. if ingestPodUID {
  811. if uidKeys, ok := podUIDKeyMap[key]; ok {
  812. keys = append(keys, uidKeys...)
  813. }
  814. } else {
  815. keys = []podKey{key}
  816. }
  817. for _, key := range keys {
  818. if _, ok := podAnnotations[key]; !ok {
  819. podAnnotations[key] = map[string]string{}
  820. }
  821. for k, l := range res.GetAnnotations() {
  822. podAnnotations[key][k] = l
  823. }
  824. }
  825. }
  826. return podAnnotations
  827. }
  828. func applyLabels(podMap map[podKey]*pod, nodeLabels map[nodeKey]map[string]string, namespaceLabels map[namespaceKey]map[string]string, podLabels map[podKey]map[string]string) {
  829. for podKey, pod := range podMap {
  830. for _, alloc := range pod.Allocations {
  831. allocLabels := alloc.Properties.Labels
  832. if allocLabels == nil {
  833. allocLabels = make(map[string]string)
  834. }
  835. nsLabels := alloc.Properties.NamespaceLabels
  836. if nsLabels == nil {
  837. nsLabels = make(map[string]string)
  838. }
  839. // Apply node labels first, then namespace labels, then pod labels
  840. // so that pod labels overwrite namespace labels, which overwrite
  841. // node labels.
  842. if nodeLabels != nil {
  843. nodeKey := newNodeKey(pod.Key.Cluster, pod.Node)
  844. if labels, ok := nodeLabels[nodeKey]; ok {
  845. for k, v := range labels {
  846. allocLabels[k] = v
  847. }
  848. }
  849. }
  850. nsKey := podKey.namespaceKey
  851. if labels, ok := namespaceLabels[nsKey]; ok {
  852. for k, v := range labels {
  853. allocLabels[k] = v
  854. nsLabels[k] = v
  855. }
  856. }
  857. if labels, ok := podLabels[podKey]; ok {
  858. for k, v := range labels {
  859. allocLabels[k] = v
  860. }
  861. }
  862. alloc.Properties.Labels = allocLabels
  863. alloc.Properties.NamespaceLabels = nsLabels
  864. }
  865. }
  866. }
  867. func applyAnnotations(podMap map[podKey]*pod, namespaceAnnotations map[string]map[string]string, podAnnotations map[podKey]map[string]string) {
  868. for key, pod := range podMap {
  869. for _, alloc := range pod.Allocations {
  870. allocAnnotations := alloc.Properties.Annotations
  871. if allocAnnotations == nil {
  872. allocAnnotations = make(map[string]string)
  873. }
  874. nsAnnotations := alloc.Properties.NamespaceAnnotations
  875. if nsAnnotations == nil {
  876. nsAnnotations = make(map[string]string)
  877. }
  878. // Apply namespace annotations first, then pod annotations so that
  879. // pod labels overwrite namespace labels.
  880. if labels, ok := namespaceAnnotations[key.Namespace]; ok {
  881. for k, v := range labels {
  882. allocAnnotations[k] = v
  883. nsAnnotations[k] = v
  884. }
  885. }
  886. if labels, ok := podAnnotations[key]; ok {
  887. for k, v := range labels {
  888. allocAnnotations[k] = v
  889. }
  890. }
  891. alloc.Properties.Annotations = allocAnnotations
  892. alloc.Properties.NamespaceAnnotations = nsAnnotations
  893. }
  894. }
  895. }
  896. func resToDeploymentLabels(resDeploymentLabels []*prom.QueryResult) map[controllerKey]map[string]string {
  897. deploymentLabels := map[controllerKey]map[string]string{}
  898. for _, res := range resDeploymentLabels {
  899. controllerKey, err := resultDeploymentKey(res, env.GetPromClusterLabel(), "namespace", "deployment")
  900. if err != nil {
  901. continue
  902. }
  903. if _, ok := deploymentLabels[controllerKey]; !ok {
  904. deploymentLabels[controllerKey] = map[string]string{}
  905. }
  906. for k, l := range res.GetLabels() {
  907. deploymentLabels[controllerKey][k] = l
  908. }
  909. }
  910. // Prune duplicate deployments. That is, if the same deployment exists with
  911. // hyphens instead of underscores, keep the one that uses hyphens.
  912. for key := range deploymentLabels {
  913. if strings.Contains(key.Controller, "_") {
  914. duplicateController := strings.Replace(key.Controller, "_", "-", -1)
  915. duplicateKey := newControllerKey(key.Cluster, key.Namespace, key.ControllerKind, duplicateController)
  916. if _, ok := deploymentLabels[duplicateKey]; ok {
  917. delete(deploymentLabels, key)
  918. }
  919. }
  920. }
  921. return deploymentLabels
  922. }
  923. func resToStatefulSetLabels(resStatefulSetLabels []*prom.QueryResult) map[controllerKey]map[string]string {
  924. statefulSetLabels := map[controllerKey]map[string]string{}
  925. for _, res := range resStatefulSetLabels {
  926. controllerKey, err := resultStatefulSetKey(res, env.GetPromClusterLabel(), "namespace", "statefulSet")
  927. if err != nil {
  928. continue
  929. }
  930. if _, ok := statefulSetLabels[controllerKey]; !ok {
  931. statefulSetLabels[controllerKey] = map[string]string{}
  932. }
  933. for k, l := range res.GetLabels() {
  934. statefulSetLabels[controllerKey][k] = l
  935. }
  936. }
  937. // Prune duplicate stateful sets. That is, if the same stateful set exists
  938. // with hyphens instead of underscores, keep the one that uses hyphens.
  939. for key := range statefulSetLabels {
  940. if strings.Contains(key.Controller, "_") {
  941. duplicateController := strings.Replace(key.Controller, "_", "-", -1)
  942. duplicateKey := newControllerKey(key.Cluster, key.Namespace, key.ControllerKind, duplicateController)
  943. if _, ok := statefulSetLabels[duplicateKey]; ok {
  944. delete(statefulSetLabels, key)
  945. }
  946. }
  947. }
  948. return statefulSetLabels
  949. }
  950. func labelsToPodControllerMap(podLabels map[podKey]map[string]string, controllerLabels map[controllerKey]map[string]string) map[podKey]controllerKey {
  951. podControllerMap := map[podKey]controllerKey{}
  952. // For each controller, turn the labels into a selector and attempt to
  953. // match it with each set of pod labels. A match indicates that the pod
  954. // belongs to the controller.
  955. for cKey, cLabels := range controllerLabels {
  956. selector := labels.Set(cLabels).AsSelectorPreValidated()
  957. for pKey, pLabels := range podLabels {
  958. // If the pod is in a different cluster or namespace, there is
  959. // no need to compare the labels.
  960. if cKey.Cluster != pKey.Cluster || cKey.Namespace != pKey.Namespace {
  961. continue
  962. }
  963. podLabelSet := labels.Set(pLabels)
  964. if selector.Matches(podLabelSet) {
  965. if _, ok := podControllerMap[pKey]; ok {
  966. log.DedupedWarningf(5, "CostModel.ComputeAllocation: PodControllerMap match already exists: %s matches %s and %s", pKey, podControllerMap[pKey], cKey)
  967. }
  968. podControllerMap[pKey] = cKey
  969. }
  970. }
  971. }
  972. return podControllerMap
  973. }
  974. func resToPodDaemonSetMap(resDaemonSetLabels []*prom.QueryResult, podUIDKeyMap map[podKey][]podKey, ingestPodUID bool) map[podKey]controllerKey {
  975. daemonSetLabels := map[podKey]controllerKey{}
  976. for _, res := range resDaemonSetLabels {
  977. controllerKey, err := resultDaemonSetKey(res, env.GetPromClusterLabel(), "namespace", "owner_name")
  978. if err != nil {
  979. continue
  980. }
  981. pod, err := res.GetString("pod")
  982. if err != nil {
  983. log.Warnf("CostModel.ComputeAllocation: DaemonSetLabel result without pod: %s", controllerKey)
  984. }
  985. key := newPodKey(controllerKey.Cluster, controllerKey.Namespace, pod)
  986. var keys []podKey
  987. if ingestPodUID {
  988. if uidKeys, ok := podUIDKeyMap[key]; ok {
  989. keys = append(keys, uidKeys...)
  990. }
  991. } else {
  992. keys = []podKey{key}
  993. }
  994. for _, key := range keys {
  995. daemonSetLabels[key] = controllerKey
  996. }
  997. }
  998. return daemonSetLabels
  999. }
  1000. func resToPodJobMap(resJobLabels []*prom.QueryResult, podUIDKeyMap map[podKey][]podKey, ingestPodUID bool) map[podKey]controllerKey {
  1001. jobLabels := map[podKey]controllerKey{}
  1002. for _, res := range resJobLabels {
  1003. controllerKey, err := resultJobKey(res, env.GetPromClusterLabel(), "namespace", "owner_name")
  1004. if err != nil {
  1005. continue
  1006. }
  1007. // Convert the name of Jobs generated by CronJobs to the name of the
  1008. // CronJob by stripping the timestamp off the end.
  1009. match := isCron.FindStringSubmatch(controllerKey.Controller)
  1010. if match != nil {
  1011. controllerKey.Controller = match[1]
  1012. }
  1013. pod, err := res.GetString("pod")
  1014. if err != nil {
  1015. log.Warnf("CostModel.ComputeAllocation: JobLabel result without pod: %s", controllerKey)
  1016. }
  1017. key := newPodKey(controllerKey.Cluster, controllerKey.Namespace, pod)
  1018. var keys []podKey
  1019. if ingestPodUID {
  1020. if uidKeys, ok := podUIDKeyMap[key]; ok {
  1021. keys = append(keys, uidKeys...)
  1022. }
  1023. } else {
  1024. keys = []podKey{key}
  1025. }
  1026. for _, key := range keys {
  1027. jobLabels[key] = controllerKey
  1028. }
  1029. }
  1030. return jobLabels
  1031. }
  1032. func resToPodReplicaSetMap(resPodsWithReplicaSetOwner []*prom.QueryResult, resReplicaSetsWithoutOwners []*prom.QueryResult, resReplicaSetsWithRolloutOwner []*prom.QueryResult, podUIDKeyMap map[podKey][]podKey, ingestPodUID bool) map[podKey]controllerKey {
  1033. // Build out set of ReplicaSets that have no owners, themselves, such that
  1034. // the ReplicaSet should be used as the owner of the Pods it controls.
  1035. // (This should exclude, for example, ReplicaSets that are controlled by
  1036. // Deployments, in which case the Deployment should be the pod's owner.)
  1037. // Additionally, add to this set of ReplicaSets those ReplicaSets that
  1038. // are owned by a Rollout
  1039. replicaSets := map[controllerKey]struct{}{}
  1040. // Create unowned ReplicaSet controller keys
  1041. for _, res := range resReplicaSetsWithoutOwners {
  1042. controllerKey, err := resultReplicaSetKey(res, env.GetPromClusterLabel(), "namespace", "replicaset")
  1043. if err != nil {
  1044. continue
  1045. }
  1046. replicaSets[controllerKey] = struct{}{}
  1047. }
  1048. // Create Rollout-owned ReplicaSet controller keys
  1049. for _, res := range resReplicaSetsWithRolloutOwner {
  1050. controllerKey, err := resultReplicaSetRolloutKey(res, env.GetPromClusterLabel(), "namespace", "replicaset")
  1051. if err != nil {
  1052. continue
  1053. }
  1054. replicaSets[controllerKey] = struct{}{}
  1055. }
  1056. // Create the mapping of Pods to ReplicaSets, ignoring any ReplicaSets that
  1057. // do not appear in the set of unowned/Rollout-owned ReplicaSets above.
  1058. podToReplicaSet := map[podKey]controllerKey{}
  1059. for _, res := range resPodsWithReplicaSetOwner {
  1060. // First, check if this pod is owned by an unowned ReplicaSet
  1061. controllerKey, err := resultReplicaSetKey(res, env.GetPromClusterLabel(), "namespace", "owner_name")
  1062. if err != nil {
  1063. continue
  1064. } else if _, ok := replicaSets[controllerKey]; !ok {
  1065. // If the pod is not owned by an unowned ReplicaSet, check if
  1066. // it's owned by a Rollout-owned ReplicaSet
  1067. controllerKey, err = resultReplicaSetRolloutKey(res, env.GetPromClusterLabel(), "namespace", "owner_name")
  1068. if err != nil {
  1069. continue
  1070. } else if _, ok := replicaSets[controllerKey]; !ok {
  1071. continue
  1072. }
  1073. }
  1074. pod, err := res.GetString("pod")
  1075. if err != nil {
  1076. log.Warnf("CostModel.ComputeAllocation: ReplicaSet result without pod: %s", controllerKey)
  1077. }
  1078. key := newPodKey(controllerKey.Cluster, controllerKey.Namespace, pod)
  1079. var keys []podKey
  1080. if ingestPodUID {
  1081. if uidKeys, ok := podUIDKeyMap[key]; ok {
  1082. keys = append(keys, uidKeys...)
  1083. }
  1084. } else {
  1085. keys = []podKey{key}
  1086. }
  1087. for _, key := range keys {
  1088. podToReplicaSet[key] = controllerKey
  1089. }
  1090. }
  1091. return podToReplicaSet
  1092. }
  1093. func applyControllersToPods(podMap map[podKey]*pod, podControllerMap map[podKey]controllerKey) {
  1094. for key, pod := range podMap {
  1095. for _, alloc := range pod.Allocations {
  1096. if controllerKey, ok := podControllerMap[key]; ok {
  1097. alloc.Properties.ControllerKind = controllerKey.ControllerKind
  1098. alloc.Properties.Controller = controllerKey.Controller
  1099. }
  1100. }
  1101. }
  1102. }
  1103. /* Service Helpers */
  1104. func getServiceLabels(resServiceLabels []*prom.QueryResult) map[serviceKey]map[string]string {
  1105. serviceLabels := map[serviceKey]map[string]string{}
  1106. for _, res := range resServiceLabels {
  1107. serviceKey, err := resultServiceKey(res, env.GetPromClusterLabel(), "namespace", "service")
  1108. if err != nil {
  1109. continue
  1110. }
  1111. if _, ok := serviceLabels[serviceKey]; !ok {
  1112. serviceLabels[serviceKey] = map[string]string{}
  1113. }
  1114. for k, l := range res.GetLabels() {
  1115. serviceLabels[serviceKey][k] = l
  1116. }
  1117. }
  1118. // Prune duplicate services. That is, if the same service exists with
  1119. // hyphens instead of underscores, keep the one that uses hyphens.
  1120. for key := range serviceLabels {
  1121. if strings.Contains(key.Service, "_") {
  1122. duplicateService := strings.Replace(key.Service, "_", "-", -1)
  1123. duplicateKey := newServiceKey(key.Cluster, key.Namespace, duplicateService)
  1124. if _, ok := serviceLabels[duplicateKey]; ok {
  1125. delete(serviceLabels, key)
  1126. }
  1127. }
  1128. }
  1129. return serviceLabels
  1130. }
  1131. func applyServicesToPods(podMap map[podKey]*pod, podLabels map[podKey]map[string]string, allocsByService map[serviceKey][]*opencost.Allocation, serviceLabels map[serviceKey]map[string]string) {
  1132. podServicesMap := map[podKey][]serviceKey{}
  1133. // For each service, turn the labels into a selector and attempt to
  1134. // match it with each set of pod labels. A match indicates that the pod
  1135. // belongs to the service.
  1136. for sKey, sLabels := range serviceLabels {
  1137. selector := labels.Set(sLabels).AsSelectorPreValidated()
  1138. for pKey, pLabels := range podLabels {
  1139. // If the pod is in a different cluster or namespace, there is
  1140. // no need to compare the labels.
  1141. if sKey.Cluster != pKey.Cluster || sKey.Namespace != pKey.Namespace {
  1142. continue
  1143. }
  1144. podLabelSet := labels.Set(pLabels)
  1145. if selector.Matches(podLabelSet) {
  1146. if _, ok := podServicesMap[pKey]; !ok {
  1147. podServicesMap[pKey] = []serviceKey{}
  1148. }
  1149. podServicesMap[pKey] = append(podServicesMap[pKey], sKey)
  1150. }
  1151. }
  1152. }
  1153. // For each allocation in each pod, attempt to find and apply the list of
  1154. // services associated with the allocation's pod.
  1155. for key, pod := range podMap {
  1156. for _, alloc := range pod.Allocations {
  1157. if sKeys, ok := podServicesMap[key]; ok {
  1158. services := []string{}
  1159. for _, sKey := range sKeys {
  1160. services = append(services, sKey.Service)
  1161. allocsByService[sKey] = append(allocsByService[sKey], alloc)
  1162. }
  1163. alloc.Properties.Services = services
  1164. }
  1165. }
  1166. }
  1167. }
  1168. func getLoadBalancerCosts(lbMap map[serviceKey]*lbCost, resLBCost, resLBActiveMins []*prom.QueryResult, resolution time.Duration, window opencost.Window) {
  1169. for _, res := range resLBActiveMins {
  1170. serviceKey, err := resultServiceKey(res, env.GetPromClusterLabel(), "namespace", "service_name")
  1171. if err != nil || len(res.Values) == 0 {
  1172. continue
  1173. }
  1174. // load balancers have interpolation for costs, we don't need to offset the resolution
  1175. lbStart, lbEnd := calculateStartAndEnd(res, resolution, window)
  1176. if lbStart.IsZero() || lbEnd.IsZero() {
  1177. log.Warnf("CostModel.ComputeAllocation: pvc %s has no running time", serviceKey)
  1178. }
  1179. lbMap[serviceKey] = &lbCost{
  1180. Start: lbStart,
  1181. End: lbEnd,
  1182. }
  1183. }
  1184. for _, res := range resLBCost {
  1185. serviceKey, err := resultServiceKey(res, env.GetPromClusterLabel(), "namespace", "service_name")
  1186. if err != nil {
  1187. continue
  1188. }
  1189. // get the ingress IP to determine if this is a private LB
  1190. ip, err := res.GetString("ingress_ip")
  1191. if err != nil {
  1192. log.Warnf("error getting ingress ip for key %s: %v, skipping", serviceKey, err)
  1193. // do not count the time that the service was being created or deleted
  1194. // ingress IP will be empty string
  1195. // only add cost to allocation when external IP is provisioned
  1196. if ip == "" {
  1197. continue
  1198. }
  1199. }
  1200. // Apply cost as price-per-hour * hours
  1201. if lb, ok := lbMap[serviceKey]; ok {
  1202. lbPricePerHr := res.Values[0].Value
  1203. // interpolate any missing data
  1204. resolutionHours := resolution.Hours()
  1205. resultHours := lb.End.Sub(lb.Start).Hours()
  1206. scaleFactor := (resolutionHours + resultHours) / resultHours
  1207. // after scaling, we can adjust the timings to reflect the interpolated data
  1208. lb.End = lb.End.Add(resolution)
  1209. lb.TotalCost += lbPricePerHr * resultHours * scaleFactor
  1210. lb.Ip = ip
  1211. lb.Private = privateIPCheck(ip)
  1212. } else {
  1213. log.DedupedWarningf(20, "CostModel: found minutes for key that does not exist: %s", serviceKey)
  1214. }
  1215. }
  1216. }
  1217. func applyLoadBalancersToPods(window opencost.Window, podMap map[podKey]*pod, lbMap map[serviceKey]*lbCost, allocsByService map[serviceKey][]*opencost.Allocation) {
  1218. for sKey, lb := range lbMap {
  1219. totalHours := 0.0
  1220. allocHours := make(map[*opencost.Allocation]float64)
  1221. allocs, ok := allocsByService[sKey]
  1222. // if there are no allocations using the service, add its cost to the Unmounted pod for its cluster
  1223. if !ok {
  1224. pod := getUnmountedPodForCluster(window, podMap, sKey.Cluster)
  1225. pod.Allocations[opencost.UnmountedSuffix].LoadBalancerCost += lb.TotalCost
  1226. pod.Allocations[opencost.UnmountedSuffix].Properties.Services = append(pod.Allocations[opencost.UnmountedSuffix].Properties.Services, sKey.Service)
  1227. }
  1228. // Add portion of load balancing cost to each allocation
  1229. // proportional to the total number of hours allocations used the load balancer
  1230. for _, alloc := range allocs {
  1231. // Determine the (start, end) of the relationship between the
  1232. // given lbCost and the associated Allocation so that a precise
  1233. // number of hours can be used to compute cumulative cost.
  1234. s, e := alloc.Start, alloc.End
  1235. if lb.Start.After(alloc.Start) {
  1236. s = lb.Start
  1237. }
  1238. if lb.End.Before(alloc.End) {
  1239. e = lb.End
  1240. }
  1241. hours := e.Sub(s).Hours()
  1242. // A negative number of hours signifies no overlap between the windows
  1243. if hours > 0 {
  1244. totalHours += hours
  1245. allocHours[alloc] = hours
  1246. }
  1247. }
  1248. // Distribute cost of service once total hours is calculated
  1249. for alloc, hours := range allocHours {
  1250. alloc.LoadBalancerCost += lb.TotalCost * hours / totalHours
  1251. }
  1252. for _, alloc := range allocs {
  1253. // reocord the hours overlapped with the allocation for the load balancer
  1254. // if there was overlap. Otherwise, record a 0.0.
  1255. // TODO: Do we really want to include load balancers that have 0 overlap
  1256. // TODO: hours with the allocation?
  1257. var hours float64 = 0.0
  1258. if _, ok := allocHours[alloc]; ok {
  1259. hours = allocHours[alloc]
  1260. }
  1261. if alloc.LoadBalancers == nil {
  1262. alloc.LoadBalancers = opencost.LbAllocations{}
  1263. }
  1264. if _, found := alloc.LoadBalancers[sKey.String()]; found {
  1265. alloc.LoadBalancers[sKey.String()].Cost += alloc.LoadBalancerCost
  1266. alloc.LoadBalancers[sKey.String()].Hours += hours
  1267. } else {
  1268. alloc.LoadBalancers[sKey.String()] = &opencost.LbAllocation{
  1269. Service: sKey.Namespace + "/" + sKey.Service,
  1270. Cost: alloc.LoadBalancerCost,
  1271. Private: lb.Private,
  1272. Ip: lb.Ip,
  1273. Hours: hours,
  1274. }
  1275. }
  1276. }
  1277. // If there was no overlap apply to Unmounted pod
  1278. if len(allocHours) == 0 {
  1279. pod := getUnmountedPodForCluster(window, podMap, sKey.Cluster)
  1280. pod.Allocations[opencost.UnmountedSuffix].LoadBalancerCost += lb.TotalCost
  1281. pod.Allocations[opencost.UnmountedSuffix].Properties.Services = append(pod.Allocations[opencost.UnmountedSuffix].Properties.Services, sKey.Service)
  1282. }
  1283. }
  1284. }
  1285. /* Node Helpers */
  1286. func applyNodeCostPerCPUHr(nodeMap map[nodeKey]*nodePricing, resNodeCostPerCPUHr []*prom.QueryResult) {
  1287. for _, res := range resNodeCostPerCPUHr {
  1288. cluster, err := res.GetString(env.GetPromClusterLabel())
  1289. if err != nil {
  1290. cluster = env.GetClusterID()
  1291. }
  1292. node, err := res.GetString("node")
  1293. if err != nil {
  1294. log.Warnf("CostModel.ComputeAllocation: Node CPU cost query result missing field: \"%s\" for node \"%s\"", err, node)
  1295. continue
  1296. }
  1297. instanceType, err := res.GetString("instance_type")
  1298. if err != nil {
  1299. log.Warnf("CostModel.ComputeAllocation: Node CPU cost query result missing field: \"%s\" for node \"%s\"", err, node)
  1300. }
  1301. providerID, err := res.GetString("provider_id")
  1302. if err != nil {
  1303. log.Warnf("CostModel.ComputeAllocation: Node CPU cost query result missing field: \"%s\" for node \"%s\"", err, node)
  1304. }
  1305. key := newNodeKey(cluster, node)
  1306. if _, ok := nodeMap[key]; !ok {
  1307. nodeMap[key] = &nodePricing{
  1308. Name: node,
  1309. NodeType: instanceType,
  1310. ProviderID: provider.ParseID(providerID),
  1311. }
  1312. }
  1313. nodeMap[key].CostPerCPUHr = res.Values[0].Value
  1314. }
  1315. }
  1316. func applyNodeCostPerRAMGiBHr(nodeMap map[nodeKey]*nodePricing, resNodeCostPerRAMGiBHr []*prom.QueryResult) {
  1317. for _, res := range resNodeCostPerRAMGiBHr {
  1318. cluster, err := res.GetString(env.GetPromClusterLabel())
  1319. if err != nil {
  1320. cluster = env.GetClusterID()
  1321. }
  1322. node, err := res.GetString("node")
  1323. if err != nil {
  1324. log.Warnf("CostModel.ComputeAllocation: Node RAM cost query result missing field: \"%s\" for node \"%s\"", err, node)
  1325. continue
  1326. }
  1327. instanceType, err := res.GetString("instance_type")
  1328. if err != nil {
  1329. log.Warnf("CostModel.ComputeAllocation: Node RAM cost query result missing field: \"%s\" for node \"%s\"", err, node)
  1330. }
  1331. providerID, err := res.GetString("provider_id")
  1332. if err != nil {
  1333. log.Warnf("CostModel.ComputeAllocation: Node RAM cost query result missing field: \"%s\" for node \"%s\"", err, node)
  1334. }
  1335. key := newNodeKey(cluster, node)
  1336. if _, ok := nodeMap[key]; !ok {
  1337. nodeMap[key] = &nodePricing{
  1338. Name: node,
  1339. NodeType: instanceType,
  1340. ProviderID: provider.ParseID(providerID),
  1341. }
  1342. }
  1343. nodeMap[key].CostPerRAMGiBHr = res.Values[0].Value
  1344. }
  1345. }
  1346. func applyNodeCostPerGPUHr(nodeMap map[nodeKey]*nodePricing, resNodeCostPerGPUHr []*prom.QueryResult) {
  1347. for _, res := range resNodeCostPerGPUHr {
  1348. cluster, err := res.GetString(env.GetPromClusterLabel())
  1349. if err != nil {
  1350. cluster = env.GetClusterID()
  1351. }
  1352. node, err := res.GetString("node")
  1353. if err != nil {
  1354. log.Warnf("CostModel.ComputeAllocation: Node GPU cost query result missing field: \"%s\" for node \"%s\"", err, node)
  1355. continue
  1356. }
  1357. instanceType, err := res.GetString("instance_type")
  1358. if err != nil {
  1359. log.Warnf("CostModel.ComputeAllocation: Node GPU cost query result missing field: \"%s\" for node \"%s\"", err, node)
  1360. }
  1361. providerID, err := res.GetString("provider_id")
  1362. if err != nil {
  1363. log.Warnf("CostModel.ComputeAllocation: Node GPU cost query result missing field: \"%s\" for node \"%s\"", err, node)
  1364. }
  1365. key := newNodeKey(cluster, node)
  1366. if _, ok := nodeMap[key]; !ok {
  1367. nodeMap[key] = &nodePricing{
  1368. Name: node,
  1369. NodeType: instanceType,
  1370. ProviderID: provider.ParseID(providerID),
  1371. }
  1372. }
  1373. nodeMap[key].CostPerGPUHr = res.Values[0].Value
  1374. }
  1375. }
  1376. func applyNodeSpot(nodeMap map[nodeKey]*nodePricing, resNodeIsSpot []*prom.QueryResult) {
  1377. for _, res := range resNodeIsSpot {
  1378. cluster, err := res.GetString(env.GetPromClusterLabel())
  1379. if err != nil {
  1380. cluster = env.GetClusterID()
  1381. }
  1382. node, err := res.GetString("node")
  1383. if err != nil {
  1384. log.Warnf("CostModel.ComputeAllocation: Node spot query result missing field: %s", err)
  1385. continue
  1386. }
  1387. key := newNodeKey(cluster, node)
  1388. if _, ok := nodeMap[key]; !ok {
  1389. log.Warnf("CostModel.ComputeAllocation: Node spot query result for missing node: %s", key)
  1390. continue
  1391. }
  1392. nodeMap[key].Preemptible = res.Values[0].Value > 0
  1393. }
  1394. }
  1395. func applyNodeDiscount(nodeMap map[nodeKey]*nodePricing, cm *CostModel) {
  1396. if cm == nil {
  1397. return
  1398. }
  1399. c, err := cm.Provider.GetConfig()
  1400. if err != nil {
  1401. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  1402. return
  1403. }
  1404. discount, err := ParsePercentString(c.Discount)
  1405. if err != nil {
  1406. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  1407. return
  1408. }
  1409. negotiatedDiscount, err := ParsePercentString(c.NegotiatedDiscount)
  1410. if err != nil {
  1411. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  1412. return
  1413. }
  1414. for _, node := range nodeMap {
  1415. // TODO GKE Reserved Instances into account
  1416. node.Discount = cm.Provider.CombinedDiscountForNode(node.NodeType, node.Preemptible, discount, negotiatedDiscount)
  1417. node.CostPerCPUHr *= (1.0 - node.Discount)
  1418. node.CostPerRAMGiBHr *= (1.0 - node.Discount)
  1419. }
  1420. }
  1421. func (cm *CostModel) applyNodesToPod(podMap map[podKey]*pod, nodeMap map[nodeKey]*nodePricing) {
  1422. for _, pod := range podMap {
  1423. for _, alloc := range pod.Allocations {
  1424. cluster := alloc.Properties.Cluster
  1425. nodeName := alloc.Properties.Node
  1426. thisNodeKey := newNodeKey(cluster, nodeName)
  1427. node := cm.getNodePricing(nodeMap, thisNodeKey)
  1428. alloc.Properties.ProviderID = node.ProviderID
  1429. alloc.CPUCost = alloc.CPUCoreHours * node.CostPerCPUHr
  1430. alloc.RAMCost = (alloc.RAMByteHours / 1024 / 1024 / 1024) * node.CostPerRAMGiBHr
  1431. alloc.GPUCost = alloc.GPUHours * node.CostPerGPUHr
  1432. }
  1433. }
  1434. }
  1435. // getCustomNodePricing converts the CostModel's configured custom pricing
  1436. // values into a nodePricing instance.
  1437. func (cm *CostModel) getCustomNodePricing(spot bool, providerID string) *nodePricing {
  1438. customPricingConfig, err := cm.Provider.GetConfig()
  1439. if err != nil {
  1440. return nil
  1441. }
  1442. cpuCostStr := customPricingConfig.CPU
  1443. gpuCostStr := customPricingConfig.GPU
  1444. ramCostStr := customPricingConfig.RAM
  1445. if spot {
  1446. cpuCostStr = customPricingConfig.SpotCPU
  1447. gpuCostStr = customPricingConfig.SpotGPU
  1448. ramCostStr = customPricingConfig.SpotRAM
  1449. }
  1450. node := &nodePricing{
  1451. Source: "custom",
  1452. ProviderID: providerID,
  1453. }
  1454. costPerCPUHr, err := strconv.ParseFloat(cpuCostStr, 64)
  1455. if err != nil {
  1456. log.Warnf("CostModel: custom pricing has illegal CPU cost: %s", cpuCostStr)
  1457. }
  1458. node.CostPerCPUHr = costPerCPUHr
  1459. costPerGPUHr, err := strconv.ParseFloat(gpuCostStr, 64)
  1460. if err != nil {
  1461. log.Warnf("CostModel: custom pricing has illegal GPU cost: %s", gpuCostStr)
  1462. }
  1463. node.CostPerGPUHr = costPerGPUHr
  1464. costPerRAMHr, err := strconv.ParseFloat(ramCostStr, 64)
  1465. if err != nil {
  1466. log.Warnf("CostModel: custom pricing has illegal RAM cost: %s", ramCostStr)
  1467. }
  1468. node.CostPerRAMGiBHr = costPerRAMHr
  1469. return node
  1470. }
  1471. // getNodePricing determines node pricing, given a key and a mapping from keys
  1472. // to their nodePricing instances, as well as the custom pricing configuration
  1473. // inherent to the CostModel instance. If custom pricing is set, use that. If
  1474. // not, use the pricing defined by the given key. If that doesn't exist, fall
  1475. // back on custom pricing as a default.
  1476. func (cm *CostModel) getNodePricing(nodeMap map[nodeKey]*nodePricing, nodeKey nodeKey) *nodePricing {
  1477. // Find the relevant nodePricing, if it exists. If not, substitute the
  1478. // custom nodePricing as a default.
  1479. node, ok := nodeMap[nodeKey]
  1480. if !ok || node == nil {
  1481. if nodeKey.Node != "" {
  1482. log.DedupedWarningf(5, "CostModel: failed to find node for %s", nodeKey)
  1483. }
  1484. // since the node pricing data is not found, and this won't change for the duration of the allocation
  1485. // build process, we can update the node map with the defaults to prevent future failed lookups
  1486. nodeMap[nodeKey] = cm.getCustomNodePricing(false, "")
  1487. return nodeMap[nodeKey]
  1488. }
  1489. // If custom pricing is enabled and can be retrieved, override detected
  1490. // node pricing with the custom values.
  1491. customPricingConfig, err := cm.Provider.GetConfig()
  1492. if err != nil {
  1493. log.Warnf("CostModel: failed to load custom pricing: %s", err)
  1494. }
  1495. if provider.CustomPricesEnabled(cm.Provider) && customPricingConfig != nil {
  1496. return cm.getCustomNodePricing(node.Preemptible, node.ProviderID)
  1497. }
  1498. node.Source = "prometheus"
  1499. // If any of the values are NaN or zero, replace them with the custom
  1500. // values as default.
  1501. // TODO:CLEANUP can't we parse these custom prices once? why do we store
  1502. // them as strings like this?
  1503. if node.CostPerCPUHr == 0 || math.IsNaN(node.CostPerCPUHr) {
  1504. log.Warnf("CostModel: node pricing has illegal CostPerCPUHr; replacing with custom pricing: %s", nodeKey)
  1505. cpuCostStr := customPricingConfig.CPU
  1506. if node.Preemptible {
  1507. cpuCostStr = customPricingConfig.SpotCPU
  1508. }
  1509. costPerCPUHr, err := strconv.ParseFloat(cpuCostStr, 64)
  1510. if err != nil {
  1511. log.Warnf("CostModel: custom pricing has illegal CPU cost: %s", cpuCostStr)
  1512. }
  1513. node.CostPerCPUHr = costPerCPUHr
  1514. node.Source += "/customCPU"
  1515. }
  1516. if math.IsNaN(node.CostPerGPUHr) {
  1517. log.Warnf("CostModel: node pricing has illegal CostPerGPUHr; replacing with custom pricing: %s", nodeKey)
  1518. gpuCostStr := customPricingConfig.GPU
  1519. if node.Preemptible {
  1520. gpuCostStr = customPricingConfig.SpotGPU
  1521. }
  1522. costPerGPUHr, err := strconv.ParseFloat(gpuCostStr, 64)
  1523. if err != nil {
  1524. log.Warnf("CostModel: custom pricing has illegal GPU cost: %s", gpuCostStr)
  1525. }
  1526. node.CostPerGPUHr = costPerGPUHr
  1527. node.Source += "/customGPU"
  1528. }
  1529. if node.CostPerRAMGiBHr == 0 || math.IsNaN(node.CostPerRAMGiBHr) {
  1530. log.Warnf("CostModel: node pricing has illegal CostPerRAMHr; replacing with custom pricing: %s", nodeKey)
  1531. ramCostStr := customPricingConfig.RAM
  1532. if node.Preemptible {
  1533. ramCostStr = customPricingConfig.SpotRAM
  1534. }
  1535. costPerRAMHr, err := strconv.ParseFloat(ramCostStr, 64)
  1536. if err != nil {
  1537. log.Warnf("CostModel: custom pricing has illegal RAM cost: %s", ramCostStr)
  1538. }
  1539. node.CostPerRAMGiBHr = costPerRAMHr
  1540. node.Source += "/customRAM"
  1541. }
  1542. // Double check each for NaNs, as there is a chance that our custom pricing
  1543. // config could, itself, contain NaNs...
  1544. if math.IsNaN(node.CostPerCPUHr) || math.IsInf(node.CostPerCPUHr, 0) {
  1545. log.Warnf("CostModel: %s: node pricing has illegal CPU value: %v (setting to 0.0)", nodeKey, node.CostPerCPUHr)
  1546. node.CostPerCPUHr = 0.0
  1547. }
  1548. if math.IsNaN(node.CostPerGPUHr) || math.IsInf(node.CostPerGPUHr, 0) {
  1549. log.Warnf("CostModel: %s: node pricing has illegal RAM value: %v (setting to 0.0)", nodeKey, node.CostPerGPUHr)
  1550. node.CostPerGPUHr = 0.0
  1551. }
  1552. if math.IsNaN(node.CostPerRAMGiBHr) || math.IsInf(node.CostPerRAMGiBHr, 0) {
  1553. log.Warnf("CostModel: %s: node pricing has illegal RAM value: %v (setting to 0.0)", nodeKey, node.CostPerRAMGiBHr)
  1554. node.CostPerRAMGiBHr = 0.0
  1555. }
  1556. return node
  1557. }
  1558. /* PV/PVC Helpers */
  1559. func buildPVMap(resolution time.Duration, pvMap map[pvKey]*pv, resPVCostPerGiBHour, resPVActiveMins, resPVMeta []*prom.QueryResult, window opencost.Window) {
  1560. for _, result := range resPVActiveMins {
  1561. key, err := resultPVKey(result, env.GetPromClusterLabel(), "persistentvolume")
  1562. if err != nil {
  1563. log.Warnf("CostModel.ComputeAllocation: pv bytes query result missing field: %s", err)
  1564. continue
  1565. }
  1566. pvStart, pvEnd := calculateStartAndEnd(result, resolution, window)
  1567. if pvStart.IsZero() || pvEnd.IsZero() {
  1568. log.Warnf("CostModel.ComputeAllocation: pv %s has no running time", key)
  1569. }
  1570. pvMap[key] = &pv{
  1571. Cluster: key.Cluster,
  1572. Name: key.PersistentVolume,
  1573. Start: pvStart,
  1574. End: pvEnd,
  1575. }
  1576. }
  1577. for _, result := range resPVCostPerGiBHour {
  1578. key, err := resultPVKey(result, env.GetPromClusterLabel(), "volumename")
  1579. if err != nil {
  1580. log.Warnf("CostModel.ComputeAllocation: thisPV bytes query result missing field: %s", err)
  1581. continue
  1582. }
  1583. if _, ok := pvMap[key]; !ok {
  1584. pvMap[key] = &pv{
  1585. Cluster: key.Cluster,
  1586. Name: key.PersistentVolume,
  1587. }
  1588. }
  1589. pvMap[key].CostPerGiBHour = result.Values[0].Value
  1590. }
  1591. for _, result := range resPVMeta {
  1592. key, err := resultPVKey(result, env.GetPromClusterLabel(), "persistentvolume")
  1593. if err != nil {
  1594. log.Warnf("error getting key for PV: %v", err)
  1595. continue
  1596. }
  1597. // only add metadata for disks that exist in the other metrics
  1598. if _, ok := pvMap[key]; ok {
  1599. provId, err := result.GetString("provider_id")
  1600. if err != nil {
  1601. log.Warnf("error getting provider id for PV %v: %v", key, err)
  1602. continue
  1603. }
  1604. pvMap[key].ProviderID = provId
  1605. }
  1606. }
  1607. }
  1608. func applyPVBytes(pvMap map[pvKey]*pv, resPVBytes []*prom.QueryResult) {
  1609. for _, res := range resPVBytes {
  1610. key, err := resultPVKey(res, env.GetPromClusterLabel(), "persistentvolume")
  1611. if err != nil {
  1612. log.Warnf("CostModel.ComputeAllocation: pv bytes query result missing field: %s", err)
  1613. continue
  1614. }
  1615. if _, ok := pvMap[key]; !ok {
  1616. log.Warnf("CostModel.ComputeAllocation: pv bytes result for missing pv: %s", key)
  1617. continue
  1618. }
  1619. pvBytesUsed := res.Values[0].Value
  1620. if pvBytesUsed < PV_USAGE_SANITY_LIMIT_BYTES {
  1621. pvMap[key].Bytes = pvBytesUsed
  1622. } else {
  1623. pvMap[key].Bytes = 0
  1624. log.Warnf("PV usage exceeds sanity limit, clamping to zero")
  1625. }
  1626. }
  1627. }
  1628. func buildPVCMap(resolution time.Duration, pvcMap map[pvcKey]*pvc, pvMap map[pvKey]*pv, resPVCInfo []*prom.QueryResult, window opencost.Window) {
  1629. for _, res := range resPVCInfo {
  1630. cluster, err := res.GetString(env.GetPromClusterLabel())
  1631. if err != nil {
  1632. cluster = env.GetClusterID()
  1633. }
  1634. values, err := res.GetStrings("persistentvolumeclaim", "storageclass", "volumename", "namespace")
  1635. if err != nil {
  1636. log.DedupedWarningf(10, "CostModel.ComputeAllocation: pvc info query result missing field: %s", err)
  1637. continue
  1638. }
  1639. namespace := values["namespace"]
  1640. name := values["persistentvolumeclaim"]
  1641. volume := values["volumename"]
  1642. storageClass := values["storageclass"]
  1643. pvKey := newPVKey(cluster, volume)
  1644. pvcKey := newPVCKey(cluster, namespace, name)
  1645. pvcStart, pvcEnd := calculateStartAndEnd(res, resolution, window)
  1646. if pvcStart.IsZero() || pvcEnd.IsZero() {
  1647. log.Warnf("CostModel.ComputeAllocation: pvc %s has no running time", pvcKey)
  1648. }
  1649. if _, ok := pvMap[pvKey]; !ok {
  1650. continue
  1651. }
  1652. pvMap[pvKey].StorageClass = storageClass
  1653. if _, ok := pvcMap[pvcKey]; !ok {
  1654. pvcMap[pvcKey] = &pvc{}
  1655. }
  1656. pvcMap[pvcKey].Name = name
  1657. pvcMap[pvcKey].Namespace = namespace
  1658. pvcMap[pvcKey].Cluster = cluster
  1659. pvcMap[pvcKey].Volume = pvMap[pvKey]
  1660. pvcMap[pvcKey].Start = pvcStart
  1661. pvcMap[pvcKey].End = pvcEnd
  1662. }
  1663. }
  1664. func applyPVCBytesRequested(pvcMap map[pvcKey]*pvc, resPVCBytesRequested []*prom.QueryResult) {
  1665. for _, res := range resPVCBytesRequested {
  1666. key, err := resultPVCKey(res, env.GetPromClusterLabel(), "namespace", "persistentvolumeclaim")
  1667. if err != nil {
  1668. continue
  1669. }
  1670. if _, ok := pvcMap[key]; !ok {
  1671. continue
  1672. }
  1673. pvcMap[key].Bytes = res.Values[0].Value
  1674. }
  1675. }
  1676. 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) {
  1677. for _, res := range resPodPVCAllocation {
  1678. cluster, err := res.GetString(env.GetPromClusterLabel())
  1679. if err != nil {
  1680. cluster = env.GetClusterID()
  1681. }
  1682. values, err := res.GetStrings("persistentvolume", "persistentvolumeclaim", "pod", "namespace")
  1683. if err != nil {
  1684. log.DedupedWarningf(5, "CostModel.ComputeAllocation: pvc allocation query result missing field: %s", err)
  1685. continue
  1686. }
  1687. namespace := values["namespace"]
  1688. pod := values["pod"]
  1689. name := values["persistentvolumeclaim"]
  1690. volume := values["persistentvolume"]
  1691. key := newPodKey(cluster, namespace, pod)
  1692. pvKey := newPVKey(cluster, volume)
  1693. pvcKey := newPVCKey(cluster, namespace, name)
  1694. var keys []podKey
  1695. if ingestPodUID {
  1696. if uidKeys, ok := podUIDKeyMap[key]; ok {
  1697. keys = append(keys, uidKeys...)
  1698. }
  1699. } else {
  1700. keys = []podKey{key}
  1701. }
  1702. for _, key := range keys {
  1703. if _, ok := pvMap[pvKey]; !ok {
  1704. log.DedupedWarningf(5, "CostModel.ComputeAllocation: pv missing for pvc allocation query result: %s", pvKey)
  1705. continue
  1706. }
  1707. if _, ok := podPVCMap[key]; !ok {
  1708. podPVCMap[key] = []*pvc{}
  1709. }
  1710. pvc, ok := pvcMap[pvcKey]
  1711. if !ok {
  1712. log.DedupedWarningf(5, "CostModel.ComputeAllocation: pvc missing for pvc allocation query: %s", pvcKey)
  1713. continue
  1714. }
  1715. if pod, ok := podMap[key]; !ok || len(pod.Allocations) <= 0 {
  1716. log.DedupedWarningf(10, "CostModel.ComputeAllocation: pvc %s for missing pod %s", pvcKey, key)
  1717. continue
  1718. }
  1719. pvc.Mounted = true
  1720. podPVCMap[key] = append(podPVCMap[key], pvc)
  1721. }
  1722. }
  1723. }
  1724. func applyPVCsToPods(window opencost.Window, podMap map[podKey]*pod, podPVCMap map[podKey][]*pvc, pvcMap map[pvcKey]*pvc) {
  1725. // Because PVCs can be shared among pods, the respective pv cost
  1726. // needs to be evenly distributed to those pods based on time
  1727. // running, as well as the amount of time the pvc was shared.
  1728. // Build a relation between every pvc to the pods that mount it
  1729. // and a window representing the interval during which they
  1730. // were associated.
  1731. pvcPodWindowMap := make(map[pvcKey]map[podKey]opencost.Window)
  1732. for thisPodKey, thisPod := range podMap {
  1733. if pvcs, ok := podPVCMap[thisPodKey]; ok {
  1734. for _, thisPVC := range pvcs {
  1735. // Determine the (start, end) of the relationship between the
  1736. // given pvc and the associated Allocation so that a precise
  1737. // number of hours can be used to compute cumulative cost.
  1738. s, e := thisPod.Start, thisPod.End
  1739. if thisPVC.Start.After(thisPod.Start) {
  1740. s = thisPVC.Start
  1741. }
  1742. if thisPVC.End.Before(thisPod.End) {
  1743. e = thisPVC.End
  1744. }
  1745. thisPVCKey := thisPVC.key()
  1746. if pvcPodWindowMap[thisPVCKey] == nil {
  1747. pvcPodWindowMap[thisPVCKey] = make(map[podKey]opencost.Window)
  1748. }
  1749. pvcPodWindowMap[thisPVCKey][thisPodKey] = opencost.NewWindow(&s, &e)
  1750. }
  1751. }
  1752. }
  1753. for thisPVCKey, podWindowMap := range pvcPodWindowMap {
  1754. // Build out a pv price coefficient for each pod with a pvc. Each
  1755. // pvc-pod relation needs a coefficient which modifies the pv cost
  1756. // such that pv costs can be shared between all pods using that pvc.
  1757. // Get single-point intervals from alloc-pvc relation windows.
  1758. intervals := getIntervalPointsFromWindows(podWindowMap)
  1759. pvc, ok := pvcMap[thisPVCKey]
  1760. if !ok {
  1761. log.Warnf("Allocation: Compute: applyPVCsToPods: missing pvc with key %s", thisPVCKey)
  1762. continue
  1763. }
  1764. if pvc == nil {
  1765. log.Warnf("Allocation: Compute: applyPVCsToPods: nil pvc with key %s", thisPVCKey)
  1766. continue
  1767. }
  1768. // Determine coefficients for each pvc-pod relation.
  1769. sharedPVCCostCoefficients, err := getPVCCostCoefficients(intervals, pvc)
  1770. if err != nil {
  1771. log.Warnf("Allocation: Compute: applyPVCsToPods: getPVCCostCoefficients: %s", err)
  1772. continue
  1773. }
  1774. // Distribute pvc costs to Allocations
  1775. for thisPodKey, coeffComponents := range sharedPVCCostCoefficients {
  1776. pod, ok2 := podMap[thisPodKey]
  1777. // If pod does not exist or the pod does not have any allocations
  1778. // get unmounted pod for cluster
  1779. if !ok2 || len(pod.Allocations) == 0 {
  1780. // Get namespace unmounted pod, as pvc will have a namespace
  1781. pod = getUnmountedPodForNamespace(window, podMap, pvc.Cluster, pvc.Namespace)
  1782. }
  1783. for _, alloc := range pod.Allocations {
  1784. s, e := pod.Start, pod.End
  1785. minutes := e.Sub(s).Minutes()
  1786. hrs := minutes / 60.0
  1787. gib := pvc.Bytes / 1024 / 1024 / 1024
  1788. cost := pvc.Volume.CostPerGiBHour * gib * hrs
  1789. byteHours := pvc.Bytes * hrs
  1790. coef := getCoefficientFromComponents(coeffComponents)
  1791. // Apply the size and cost of the pv to the allocation, each
  1792. // weighted by count (i.e. the number of containers in the pod)
  1793. // record the amount of total PVBytes Hours attributable to a given pv
  1794. if alloc.PVs == nil {
  1795. alloc.PVs = opencost.PVAllocations{}
  1796. }
  1797. pvKey := opencost.PVKey{
  1798. Cluster: pvc.Volume.Cluster,
  1799. Name: pvc.Volume.Name,
  1800. }
  1801. // Both Cost and byteHours should be multiplied by the coef and divided by count
  1802. // so that if all allocations with a given pv key are summed the result of those
  1803. // would be equal to the values of the original pv
  1804. count := float64(len(pod.Allocations))
  1805. alloc.PVs[pvKey] = &opencost.PVAllocation{
  1806. ByteHours: byteHours * coef / count,
  1807. Cost: cost * coef / count,
  1808. ProviderID: pvc.Volume.ProviderID,
  1809. }
  1810. }
  1811. }
  1812. }
  1813. }
  1814. func applyUnmountedPVs(window opencost.Window, podMap map[podKey]*pod, pvMap map[pvKey]*pv, pvcMap map[pvcKey]*pvc) {
  1815. for _, pv := range pvMap {
  1816. mounted := false
  1817. for _, pvc := range pvcMap {
  1818. if pvc.Volume == nil {
  1819. continue
  1820. }
  1821. if pvc.Volume == pv {
  1822. mounted = true
  1823. break
  1824. }
  1825. }
  1826. if !mounted {
  1827. // a pv without a pvc will not have a namespace, so get the cluster unmounted pod
  1828. pod := getUnmountedPodForCluster(window, podMap, pv.Cluster)
  1829. // Calculate pv Cost
  1830. // Unmounted pv should have correct keyso it can still reconcile
  1831. thisPVKey := opencost.PVKey{
  1832. Cluster: pv.Cluster,
  1833. Name: pv.Name,
  1834. }
  1835. gib := pv.Bytes / 1024 / 1024 / 1024
  1836. hrs := pv.minutes() / 60.0
  1837. cost := pv.CostPerGiBHour * gib * hrs
  1838. unmountedPVs := opencost.PVAllocations{
  1839. thisPVKey: {
  1840. ByteHours: pv.Bytes * hrs,
  1841. Cost: cost,
  1842. },
  1843. }
  1844. pod.Allocations[opencost.UnmountedSuffix].PVs = pod.Allocations[opencost.UnmountedSuffix].PVs.Add(unmountedPVs)
  1845. }
  1846. }
  1847. }
  1848. func applyUnmountedPVCs(window opencost.Window, podMap map[podKey]*pod, pvcMap map[pvcKey]*pvc) {
  1849. for _, pvc := range pvcMap {
  1850. if !pvc.Mounted && pvc.Volume != nil {
  1851. // Get namespace unmounted pod, as pvc will have a namespace
  1852. pod := getUnmountedPodForNamespace(window, podMap, pvc.Cluster, pvc.Namespace)
  1853. // Calculate pv Cost
  1854. // Unmounted pv should have correct key so it can still reconcile
  1855. thisPVKey := opencost.PVKey{
  1856. Cluster: pvc.Volume.Cluster,
  1857. Name: pvc.Volume.Name,
  1858. }
  1859. // Use the Volume Bytes here because pvc bytes could be different,
  1860. // however the pv bytes are what are going to determine cost
  1861. gib := pvc.Volume.Bytes / 1024 / 1024 / 1024
  1862. hrs := pvc.Volume.minutes() / 60.0
  1863. cost := pvc.Volume.CostPerGiBHour * gib * hrs
  1864. unmountedPVs := opencost.PVAllocations{
  1865. thisPVKey: {
  1866. ByteHours: pvc.Volume.Bytes * hrs,
  1867. Cost: cost,
  1868. },
  1869. }
  1870. pod.Allocations[opencost.UnmountedSuffix].PVs = pod.Allocations[opencost.UnmountedSuffix].PVs.Add(unmountedPVs)
  1871. }
  1872. }
  1873. }
  1874. /* Helper Helpers */
  1875. // getUnmountedPodForCluster retrieve the unmounted pod for a cluster and create it if it does not exist
  1876. func getUnmountedPodForCluster(window opencost.Window, podMap map[podKey]*pod, cluster string) *pod {
  1877. container := opencost.UnmountedSuffix
  1878. podName := opencost.UnmountedSuffix
  1879. namespace := opencost.UnmountedSuffix
  1880. node := ""
  1881. thisPodKey := getUnmountedPodKey(cluster)
  1882. // Initialize pod and container if they do not already exist
  1883. thisPod, ok := podMap[thisPodKey]
  1884. if !ok {
  1885. thisPod = &pod{
  1886. Window: window.Clone(),
  1887. Start: *window.Start(),
  1888. End: *window.End(),
  1889. Key: thisPodKey,
  1890. Allocations: map[string]*opencost.Allocation{},
  1891. }
  1892. thisPod.appendContainer(container)
  1893. thisPod.Allocations[container].Properties.Cluster = cluster
  1894. thisPod.Allocations[container].Properties.Node = node
  1895. thisPod.Allocations[container].Properties.Namespace = namespace
  1896. thisPod.Allocations[container].Properties.Pod = podName
  1897. thisPod.Allocations[container].Properties.Container = container
  1898. thisPod.Node = node
  1899. podMap[thisPodKey] = thisPod
  1900. }
  1901. return thisPod
  1902. }
  1903. // getUnmountedPodForNamespace is as getUnmountedPodForCluster, but keys allocation property pod/namespace field off namespace
  1904. // This creates or adds allocations to an unmounted pod in the specified namespace, rather than in __unmounted__
  1905. func getUnmountedPodForNamespace(window opencost.Window, podMap map[podKey]*pod, cluster string, namespace string) *pod {
  1906. container := opencost.UnmountedSuffix
  1907. podName := fmt.Sprintf("%s-unmounted-pvcs", namespace)
  1908. node := ""
  1909. thisPodKey := newPodKey(cluster, namespace, podName)
  1910. // Initialize pod and container if they do not already exist
  1911. thisPod, ok := podMap[thisPodKey]
  1912. if !ok {
  1913. thisPod = &pod{
  1914. Window: window.Clone(),
  1915. Start: *window.Start(),
  1916. End: *window.End(),
  1917. Key: thisPodKey,
  1918. Allocations: map[string]*opencost.Allocation{},
  1919. }
  1920. thisPod.appendContainer(container)
  1921. thisPod.Allocations[container].Properties.Cluster = cluster
  1922. thisPod.Allocations[container].Properties.Node = node
  1923. thisPod.Allocations[container].Properties.Namespace = namespace
  1924. thisPod.Allocations[container].Properties.Pod = podName
  1925. thisPod.Allocations[container].Properties.Container = container
  1926. thisPod.Node = node
  1927. podMap[thisPodKey] = thisPod
  1928. }
  1929. return thisPod
  1930. }
  1931. func calculateStartAndEnd(result *prom.QueryResult, resolution time.Duration, window opencost.Window) (time.Time, time.Time) {
  1932. // Start and end for a range vector are pulled from the timestamps of the
  1933. // first and final values in the range. There is no "offsetting" required
  1934. // of the start or the end, as we used to do. If you query for a duration
  1935. // of time that is divisible by the given resolution, and set the end time
  1936. // to be precisely the end of the window, Prometheus should give all the
  1937. // relevant timestamps.
  1938. //
  1939. // E.g. avg(kube_pod_container_status_running{}) by (pod, namespace)[1h:1m]
  1940. // with time=01:00:00 will return, for a pod running the entire time,
  1941. // 61 timestamps where the first is 00:00:00 and the last is 01:00:00.
  1942. s := time.Unix(int64(result.Values[0].Timestamp), 0).UTC()
  1943. e := time.Unix(int64(result.Values[len(result.Values)-1].Timestamp), 0).UTC()
  1944. // The only corner-case here is what to do if you only get one timestamp.
  1945. // This dilemma still requires the use of the resolution, and can be
  1946. // clamped using the window. In this case, we want to honor the existence
  1947. // of the pod by giving "one resolution" worth of duration, half on each
  1948. // side of the given timestamp.
  1949. if s.Equal(e) {
  1950. s = s.Add(-1 * resolution / time.Duration(2))
  1951. e = e.Add(resolution / time.Duration(2))
  1952. }
  1953. if s.Before(*window.Start()) {
  1954. s = *window.Start()
  1955. }
  1956. if e.After(*window.End()) {
  1957. e = *window.End()
  1958. }
  1959. return s, e
  1960. }