allocation_helpers.go 71 KB

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