allocation_helpers.go 78 KB

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