allocation_helpers.go 77 KB

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