allocation_helpers.go 69 KB

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