allocation_helpers.go 76 KB

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