allocation_helpers.go 71 KB

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