allocation_helpers.go 76 KB

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