allocation_helpers.go 75 KB

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