allocation_helpers.go 65 KB

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