allocation_helpers.go 73 KB

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