allocation_helpers.go 66 KB

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