allocation_helpers.go 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214
  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, resReplicaSetsWithRolloutOwner []*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. // Additionally, add to this set of ReplicaSets those ReplicaSets that
  975. // are owned by a Rollout
  976. replicaSets := map[controllerKey]struct{}{}
  977. // Create unowned ReplicaSet controller keys
  978. for _, res := range resReplicaSetsWithoutOwners {
  979. controllerKey, err := resultReplicaSetKey(res, env.GetPromClusterLabel(), "namespace", "replicaset")
  980. if err != nil {
  981. continue
  982. }
  983. replicaSets[controllerKey] = struct{}{}
  984. }
  985. // Create Rollout-owned ReplicaSet controller keys
  986. for _, res := range resReplicaSetsWithRolloutOwner {
  987. controllerKey, err := resultReplicaSetRolloutKey(res, env.GetPromClusterLabel(), "namespace", "replicaset")
  988. if err != nil {
  989. continue
  990. }
  991. replicaSets[controllerKey] = struct{}{}
  992. }
  993. // Create the mapping of Pods to ReplicaSets, ignoring any ReplicaSets that
  994. // do not appear in the set of unowned/Rollout-owned ReplicaSets above.
  995. podToReplicaSet := map[podKey]controllerKey{}
  996. for _, res := range resPodsWithReplicaSetOwner {
  997. // First, check if this pod is owned by an unowned ReplicaSet
  998. controllerKey, err := resultReplicaSetKey(res, env.GetPromClusterLabel(), "namespace", "owner_name")
  999. if err != nil {
  1000. continue
  1001. } else if _, ok := replicaSets[controllerKey]; !ok {
  1002. // If the pod is not owned by an unowned ReplicaSet, check if
  1003. // it's owned by a Rollout-owned ReplicaSet
  1004. controllerKey, err = resultReplicaSetRolloutKey(res, env.GetPromClusterLabel(), "namespace", "owner_name")
  1005. if err != nil {
  1006. continue
  1007. } else if _, ok := replicaSets[controllerKey]; !ok {
  1008. continue
  1009. }
  1010. }
  1011. pod, err := res.GetString("pod")
  1012. if err != nil {
  1013. log.Warnf("CostModel.ComputeAllocation: ReplicaSet result without pod: %s", controllerKey)
  1014. }
  1015. key := newPodKey(controllerKey.Cluster, controllerKey.Namespace, pod)
  1016. var keys []podKey
  1017. if ingestPodUID {
  1018. if uidKeys, ok := podUIDKeyMap[key]; ok {
  1019. keys = append(keys, uidKeys...)
  1020. }
  1021. } else {
  1022. keys = []podKey{key}
  1023. }
  1024. for _, key := range keys {
  1025. podToReplicaSet[key] = controllerKey
  1026. }
  1027. }
  1028. return podToReplicaSet
  1029. }
  1030. func applyControllersToPods(podMap map[podKey]*pod, podControllerMap map[podKey]controllerKey) {
  1031. for key, pod := range podMap {
  1032. for _, alloc := range pod.Allocations {
  1033. if controllerKey, ok := podControllerMap[key]; ok {
  1034. alloc.Properties.ControllerKind = controllerKey.ControllerKind
  1035. alloc.Properties.Controller = controllerKey.Controller
  1036. }
  1037. }
  1038. }
  1039. }
  1040. /* Service Helpers */
  1041. func getServiceLabels(resServiceLabels []*prom.QueryResult) map[serviceKey]map[string]string {
  1042. serviceLabels := map[serviceKey]map[string]string{}
  1043. for _, res := range resServiceLabels {
  1044. serviceKey, err := resultServiceKey(res, env.GetPromClusterLabel(), "namespace", "service")
  1045. if err != nil {
  1046. continue
  1047. }
  1048. if _, ok := serviceLabels[serviceKey]; !ok {
  1049. serviceLabels[serviceKey] = map[string]string{}
  1050. }
  1051. for k, l := range res.GetLabels() {
  1052. serviceLabels[serviceKey][k] = l
  1053. }
  1054. }
  1055. // Prune duplicate services. That is, if the same service exists with
  1056. // hyphens instead of underscores, keep the one that uses hyphens.
  1057. for key := range serviceLabels {
  1058. if strings.Contains(key.Service, "_") {
  1059. duplicateService := strings.Replace(key.Service, "_", "-", -1)
  1060. duplicateKey := newServiceKey(key.Cluster, key.Namespace, duplicateService)
  1061. if _, ok := serviceLabels[duplicateKey]; ok {
  1062. delete(serviceLabels, key)
  1063. }
  1064. }
  1065. }
  1066. return serviceLabels
  1067. }
  1068. func applyServicesToPods(podMap map[podKey]*pod, podLabels map[podKey]map[string]string, allocsByService map[serviceKey][]*kubecost.Allocation, serviceLabels map[serviceKey]map[string]string) {
  1069. podServicesMap := map[podKey][]serviceKey{}
  1070. // For each service, turn the labels into a selector and attempt to
  1071. // match it with each set of pod labels. A match indicates that the pod
  1072. // belongs to the service.
  1073. for sKey, sLabels := range serviceLabels {
  1074. selector := labels.Set(sLabels).AsSelectorPreValidated()
  1075. for pKey, pLabels := range podLabels {
  1076. // If the pod is in a different cluster or namespace, there is
  1077. // no need to compare the labels.
  1078. if sKey.Cluster != pKey.Cluster || sKey.Namespace != pKey.Namespace {
  1079. continue
  1080. }
  1081. podLabelSet := labels.Set(pLabels)
  1082. if selector.Matches(podLabelSet) {
  1083. if _, ok := podServicesMap[pKey]; !ok {
  1084. podServicesMap[pKey] = []serviceKey{}
  1085. }
  1086. podServicesMap[pKey] = append(podServicesMap[pKey], sKey)
  1087. }
  1088. }
  1089. }
  1090. // For each allocation in each pod, attempt to find and apply the list of
  1091. // services associated with the allocation's pod.
  1092. for key, pod := range podMap {
  1093. for _, alloc := range pod.Allocations {
  1094. if sKeys, ok := podServicesMap[key]; ok {
  1095. services := []string{}
  1096. for _, sKey := range sKeys {
  1097. services = append(services, sKey.Service)
  1098. allocsByService[sKey] = append(allocsByService[sKey], alloc)
  1099. }
  1100. alloc.Properties.Services = services
  1101. }
  1102. }
  1103. }
  1104. }
  1105. func getLoadBalancerCosts(lbMap map[serviceKey]*lbCost, resLBCost, resLBActiveMins []*prom.QueryResult, resolution time.Duration) {
  1106. for _, res := range resLBActiveMins {
  1107. serviceKey, err := resultServiceKey(res, env.GetPromClusterLabel(), "namespace", "service_name")
  1108. if err != nil || len(res.Values) == 0 {
  1109. continue
  1110. }
  1111. lbStart, lbEnd := calculateStartAndEnd(res, resolution)
  1112. if lbStart.IsZero() || lbEnd.IsZero() {
  1113. log.Warnf("CostModel.ComputeAllocation: pvc %s has no running time", serviceKey)
  1114. }
  1115. lbMap[serviceKey] = &lbCost{
  1116. Start: lbStart,
  1117. End: lbEnd,
  1118. }
  1119. }
  1120. for _, res := range resLBCost {
  1121. serviceKey, err := resultServiceKey(res, env.GetPromClusterLabel(), "namespace", "service_name")
  1122. if err != nil {
  1123. continue
  1124. }
  1125. // Apply cost as price-per-hour * hours
  1126. if lb, ok := lbMap[serviceKey]; ok {
  1127. lbPricePerHr := res.Values[0].Value
  1128. hours := lb.End.Sub(lb.Start).Hours()
  1129. lb.TotalCost += lbPricePerHr * hours
  1130. } else {
  1131. log.DedupedWarningf(20, "CostModel: found minutes for key that does not exist: %s", serviceKey)
  1132. }
  1133. }
  1134. }
  1135. func applyLoadBalancersToPods(window kubecost.Window, podMap map[podKey]*pod, lbMap map[serviceKey]*lbCost, allocsByService map[serviceKey][]*kubecost.Allocation) {
  1136. for sKey, lb := range lbMap {
  1137. totalHours := 0.0
  1138. allocHours := make(map[*kubecost.Allocation]float64)
  1139. allocs, ok := allocsByService[sKey]
  1140. // if there are no allocations using the service, add its cost to the Unmounted pod for its cluster
  1141. if !ok {
  1142. pod := getUnmountedPodForCluster(window, podMap, sKey.Cluster)
  1143. pod.Allocations[kubecost.UnmountedSuffix].LoadBalancerCost += lb.TotalCost
  1144. pod.Allocations[kubecost.UnmountedSuffix].Properties.Services = append(pod.Allocations[kubecost.UnmountedSuffix].Properties.Services, sKey.Service)
  1145. }
  1146. // Add portion of load balancing cost to each allocation
  1147. // proportional to the total number of hours allocations used the load balancer
  1148. for _, alloc := range allocs {
  1149. // Determine the (start, end) of the relationship between the
  1150. // given lbCost and the associated Allocation so that a precise
  1151. // number of hours can be used to compute cumulative cost.
  1152. s, e := alloc.Start, alloc.End
  1153. if lb.Start.After(alloc.Start) {
  1154. s = lb.Start
  1155. }
  1156. if lb.End.Before(alloc.End) {
  1157. e = lb.End
  1158. }
  1159. hours := e.Sub(s).Hours()
  1160. // A negative number of hours signifies no overlap between the windows
  1161. if hours > 0 {
  1162. totalHours += hours
  1163. allocHours[alloc] = hours
  1164. }
  1165. }
  1166. // Distribute cost of service once total hours is calculated
  1167. for alloc, hours := range allocHours {
  1168. alloc.LoadBalancerCost += lb.TotalCost * hours / totalHours
  1169. }
  1170. // If there was no overlap apply to Unmounted pod
  1171. if len(allocHours) == 0 {
  1172. pod := getUnmountedPodForCluster(window, podMap, sKey.Cluster)
  1173. pod.Allocations[kubecost.UnmountedSuffix].LoadBalancerCost += lb.TotalCost
  1174. pod.Allocations[kubecost.UnmountedSuffix].Properties.Services = append(pod.Allocations[kubecost.UnmountedSuffix].Properties.Services, sKey.Service)
  1175. }
  1176. }
  1177. }
  1178. /* Node Helpers */
  1179. func applyNodeCostPerCPUHr(nodeMap map[nodeKey]*nodePricing, resNodeCostPerCPUHr []*prom.QueryResult) {
  1180. for _, res := range resNodeCostPerCPUHr {
  1181. cluster, err := res.GetString(env.GetPromClusterLabel())
  1182. if err != nil {
  1183. cluster = env.GetClusterID()
  1184. }
  1185. node, err := res.GetString("node")
  1186. if err != nil {
  1187. log.Warnf("CostModel.ComputeAllocation: Node CPU cost query result missing field: %s", err)
  1188. continue
  1189. }
  1190. instanceType, err := res.GetString("instance_type")
  1191. if err != nil {
  1192. log.Warnf("CostModel.ComputeAllocation: Node CPU cost query result missing field: %s", err)
  1193. continue
  1194. }
  1195. providerID, err := res.GetString("provider_id")
  1196. if err != nil {
  1197. log.Warnf("CostModel.ComputeAllocation: Node CPU cost query result missing field: %s", err)
  1198. continue
  1199. }
  1200. key := newNodeKey(cluster, node)
  1201. if _, ok := nodeMap[key]; !ok {
  1202. nodeMap[key] = &nodePricing{
  1203. Name: node,
  1204. NodeType: instanceType,
  1205. ProviderID: cloud.ParseID(providerID),
  1206. }
  1207. }
  1208. nodeMap[key].CostPerCPUHr = res.Values[0].Value
  1209. }
  1210. }
  1211. func applyNodeCostPerRAMGiBHr(nodeMap map[nodeKey]*nodePricing, resNodeCostPerRAMGiBHr []*prom.QueryResult) {
  1212. for _, res := range resNodeCostPerRAMGiBHr {
  1213. cluster, err := res.GetString(env.GetPromClusterLabel())
  1214. if err != nil {
  1215. cluster = env.GetClusterID()
  1216. }
  1217. node, err := res.GetString("node")
  1218. if err != nil {
  1219. log.Warnf("CostModel.ComputeAllocation: Node RAM cost query result missing field: %s", err)
  1220. continue
  1221. }
  1222. instanceType, err := res.GetString("instance_type")
  1223. if err != nil {
  1224. log.Warnf("CostModel.ComputeAllocation: Node RAM cost query result missing field: %s", err)
  1225. continue
  1226. }
  1227. providerID, err := res.GetString("provider_id")
  1228. if err != nil {
  1229. log.Warnf("CostModel.ComputeAllocation: Node RAM cost query result missing field: %s", err)
  1230. continue
  1231. }
  1232. key := newNodeKey(cluster, node)
  1233. if _, ok := nodeMap[key]; !ok {
  1234. nodeMap[key] = &nodePricing{
  1235. Name: node,
  1236. NodeType: instanceType,
  1237. ProviderID: cloud.ParseID(providerID),
  1238. }
  1239. }
  1240. nodeMap[key].CostPerRAMGiBHr = res.Values[0].Value
  1241. }
  1242. }
  1243. func applyNodeCostPerGPUHr(nodeMap map[nodeKey]*nodePricing, resNodeCostPerGPUHr []*prom.QueryResult) {
  1244. for _, res := range resNodeCostPerGPUHr {
  1245. cluster, err := res.GetString(env.GetPromClusterLabel())
  1246. if err != nil {
  1247. cluster = env.GetClusterID()
  1248. }
  1249. node, err := res.GetString("node")
  1250. if err != nil {
  1251. log.Warnf("CostModel.ComputeAllocation: Node GPU cost query result missing field: %s", err)
  1252. continue
  1253. }
  1254. instanceType, err := res.GetString("instance_type")
  1255. if err != nil {
  1256. log.Warnf("CostModel.ComputeAllocation: Node GPU cost query result missing field: %s", err)
  1257. continue
  1258. }
  1259. providerID, err := res.GetString("provider_id")
  1260. if err != nil {
  1261. log.Warnf("CostModel.ComputeAllocation: Node GPU cost query result missing field: %s", err)
  1262. continue
  1263. }
  1264. key := newNodeKey(cluster, node)
  1265. if _, ok := nodeMap[key]; !ok {
  1266. nodeMap[key] = &nodePricing{
  1267. Name: node,
  1268. NodeType: instanceType,
  1269. ProviderID: cloud.ParseID(providerID),
  1270. }
  1271. }
  1272. nodeMap[key].CostPerGPUHr = res.Values[0].Value
  1273. }
  1274. }
  1275. func applyNodeSpot(nodeMap map[nodeKey]*nodePricing, resNodeIsSpot []*prom.QueryResult) {
  1276. for _, res := range resNodeIsSpot {
  1277. cluster, err := res.GetString(env.GetPromClusterLabel())
  1278. if err != nil {
  1279. cluster = env.GetClusterID()
  1280. }
  1281. node, err := res.GetString("node")
  1282. if err != nil {
  1283. log.Warnf("CostModel.ComputeAllocation: Node spot query result missing field: %s", err)
  1284. continue
  1285. }
  1286. key := newNodeKey(cluster, node)
  1287. if _, ok := nodeMap[key]; !ok {
  1288. log.Warnf("CostModel.ComputeAllocation: Node spot query result for missing node: %s", key)
  1289. continue
  1290. }
  1291. nodeMap[key].Preemptible = res.Values[0].Value > 0
  1292. }
  1293. }
  1294. func applyNodeDiscount(nodeMap map[nodeKey]*nodePricing, cm *CostModel) {
  1295. if cm == nil {
  1296. return
  1297. }
  1298. c, err := cm.Provider.GetConfig()
  1299. if err != nil {
  1300. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  1301. return
  1302. }
  1303. discount, err := ParsePercentString(c.Discount)
  1304. if err != nil {
  1305. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  1306. return
  1307. }
  1308. negotiatedDiscount, err := ParsePercentString(c.NegotiatedDiscount)
  1309. if err != nil {
  1310. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  1311. return
  1312. }
  1313. for _, node := range nodeMap {
  1314. // TODO GKE Reserved Instances into account
  1315. node.Discount = cm.Provider.CombinedDiscountForNode(node.NodeType, node.Preemptible, discount, negotiatedDiscount)
  1316. node.CostPerCPUHr *= (1.0 - node.Discount)
  1317. node.CostPerRAMGiBHr *= (1.0 - node.Discount)
  1318. }
  1319. }
  1320. func (cm *CostModel) applyNodesToPod(podMap map[podKey]*pod, nodeMap map[nodeKey]*nodePricing) {
  1321. for _, pod := range podMap {
  1322. for _, alloc := range pod.Allocations {
  1323. cluster := alloc.Properties.Cluster
  1324. nodeName := alloc.Properties.Node
  1325. thisNodeKey := newNodeKey(cluster, nodeName)
  1326. node := cm.getNodePricing(nodeMap, thisNodeKey)
  1327. alloc.Properties.ProviderID = node.ProviderID
  1328. alloc.CPUCost = alloc.CPUCoreHours * node.CostPerCPUHr
  1329. alloc.RAMCost = (alloc.RAMByteHours / 1024 / 1024 / 1024) * node.CostPerRAMGiBHr
  1330. alloc.GPUCost = alloc.GPUHours * node.CostPerGPUHr
  1331. }
  1332. }
  1333. }
  1334. // getCustomNodePricing converts the CostModel's configured custom pricing
  1335. // values into a nodePricing instance.
  1336. func (cm *CostModel) getCustomNodePricing(spot bool) *nodePricing {
  1337. customPricingConfig, err := cm.Provider.GetConfig()
  1338. if err != nil {
  1339. return nil
  1340. }
  1341. cpuCostStr := customPricingConfig.CPU
  1342. gpuCostStr := customPricingConfig.GPU
  1343. ramCostStr := customPricingConfig.RAM
  1344. if spot {
  1345. cpuCostStr = customPricingConfig.SpotCPU
  1346. gpuCostStr = customPricingConfig.SpotGPU
  1347. ramCostStr = customPricingConfig.SpotRAM
  1348. }
  1349. node := &nodePricing{Source: "custom"}
  1350. costPerCPUHr, err := strconv.ParseFloat(cpuCostStr, 64)
  1351. if err != nil {
  1352. log.Warnf("CostModel: custom pricing has illegal CPU cost: %s", cpuCostStr)
  1353. }
  1354. node.CostPerCPUHr = costPerCPUHr
  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. costPerRAMHr, err := strconv.ParseFloat(ramCostStr, 64)
  1361. if err != nil {
  1362. log.Warnf("CostModel: custom pricing has illegal RAM cost: %s", ramCostStr)
  1363. }
  1364. node.CostPerRAMGiBHr = costPerRAMHr
  1365. return node
  1366. }
  1367. // getNodePricing determines node pricing, given a key and a mapping from keys
  1368. // to their nodePricing instances, as well as the custom pricing configuration
  1369. // inherent to the CostModel instance. If custom pricing is set, use that. If
  1370. // not, use the pricing defined by the given key. If that doesn't exist, fall
  1371. // back on custom pricing as a default.
  1372. func (cm *CostModel) getNodePricing(nodeMap map[nodeKey]*nodePricing, nodeKey nodeKey) *nodePricing {
  1373. // Find the relevant nodePricing, if it exists. If not, substitute the
  1374. // custom nodePricing as a default.
  1375. node, ok := nodeMap[nodeKey]
  1376. if !ok || node == nil {
  1377. if nodeKey.Node != "" {
  1378. log.DedupedWarningf(5, "CostModel: failed to find node for %s", nodeKey)
  1379. }
  1380. return cm.getCustomNodePricing(false)
  1381. }
  1382. // If custom pricing is enabled and can be retrieved, override detected
  1383. // node pricing with the custom values.
  1384. customPricingConfig, err := cm.Provider.GetConfig()
  1385. if err != nil {
  1386. log.Warnf("CostModel: failed to load custom pricing: %s", err)
  1387. }
  1388. if cloud.CustomPricesEnabled(cm.Provider) && customPricingConfig != nil {
  1389. return cm.getCustomNodePricing(node.Preemptible)
  1390. }
  1391. node.Source = "prometheus"
  1392. // If any of the values are NaN or zero, replace them with the custom
  1393. // values as default.
  1394. // TODO:CLEANUP can't we parse these custom prices once? why do we store
  1395. // them as strings like this?
  1396. if node.CostPerCPUHr == 0 || math.IsNaN(node.CostPerCPUHr) {
  1397. log.Warnf("CostModel: node pricing has illegal CostPerCPUHr; replacing with custom pricing: %s", nodeKey)
  1398. cpuCostStr := customPricingConfig.CPU
  1399. if node.Preemptible {
  1400. cpuCostStr = customPricingConfig.SpotCPU
  1401. }
  1402. costPerCPUHr, err := strconv.ParseFloat(cpuCostStr, 64)
  1403. if err != nil {
  1404. log.Warnf("CostModel: custom pricing has illegal CPU cost: %s", cpuCostStr)
  1405. }
  1406. node.CostPerCPUHr = costPerCPUHr
  1407. node.Source += "/customCPU"
  1408. }
  1409. if math.IsNaN(node.CostPerGPUHr) {
  1410. log.Warnf("CostModel: node pricing has illegal CostPerGPUHr; replacing with custom pricing: %s", nodeKey)
  1411. gpuCostStr := customPricingConfig.GPU
  1412. if node.Preemptible {
  1413. gpuCostStr = customPricingConfig.SpotGPU
  1414. }
  1415. costPerGPUHr, err := strconv.ParseFloat(gpuCostStr, 64)
  1416. if err != nil {
  1417. log.Warnf("CostModel: custom pricing has illegal GPU cost: %s", gpuCostStr)
  1418. }
  1419. node.CostPerGPUHr = costPerGPUHr
  1420. node.Source += "/customGPU"
  1421. }
  1422. if node.CostPerRAMGiBHr == 0 || math.IsNaN(node.CostPerRAMGiBHr) {
  1423. log.Warnf("CostModel: node pricing has illegal CostPerRAMHr; replacing with custom pricing: %s", nodeKey)
  1424. ramCostStr := customPricingConfig.RAM
  1425. if node.Preemptible {
  1426. ramCostStr = customPricingConfig.SpotRAM
  1427. }
  1428. costPerRAMHr, err := strconv.ParseFloat(ramCostStr, 64)
  1429. if err != nil {
  1430. log.Warnf("CostModel: custom pricing has illegal RAM cost: %s", ramCostStr)
  1431. }
  1432. node.CostPerRAMGiBHr = costPerRAMHr
  1433. node.Source += "/customRAM"
  1434. }
  1435. return node
  1436. }
  1437. /* PV/PVC Helpers */
  1438. func buildPVMap(resolution time.Duration, pvMap map[pvKey]*pv, resPVCostPerGiBHour, resPVActiveMins []*prom.QueryResult) {
  1439. for _, result := range resPVActiveMins {
  1440. key, err := resultPVKey(result, env.GetPromClusterLabel(), "persistentvolume")
  1441. if err != nil {
  1442. log.Warnf("CostModel.ComputeAllocation: pv bytes query result missing field: %s", err)
  1443. continue
  1444. }
  1445. pvStart, pvEnd := calculateStartAndEnd(result, resolution)
  1446. if pvStart.IsZero() || pvEnd.IsZero() {
  1447. log.Warnf("CostModel.ComputeAllocation: pv %s has no running time", key)
  1448. }
  1449. pvMap[key] = &pv{
  1450. Cluster: key.Cluster,
  1451. Name: key.PersistentVolume,
  1452. Start: pvStart,
  1453. End: pvEnd,
  1454. }
  1455. }
  1456. for _, result := range resPVCostPerGiBHour {
  1457. key, err := resultPVKey(result, env.GetPromClusterLabel(), "volumename")
  1458. if err != nil {
  1459. log.Warnf("CostModel.ComputeAllocation: thisPV bytes query result missing field: %s", err)
  1460. continue
  1461. }
  1462. if _, ok := pvMap[key]; !ok {
  1463. pvMap[key] = &pv{
  1464. Cluster: key.Cluster,
  1465. Name: key.PersistentVolume,
  1466. }
  1467. }
  1468. pvMap[key].CostPerGiBHour = result.Values[0].Value
  1469. }
  1470. }
  1471. func applyPVBytes(pvMap map[pvKey]*pv, resPVBytes []*prom.QueryResult) {
  1472. for _, res := range resPVBytes {
  1473. key, err := resultPVKey(res, env.GetPromClusterLabel(), "persistentvolume")
  1474. if err != nil {
  1475. log.Warnf("CostModel.ComputeAllocation: pv bytes query result missing field: %s", err)
  1476. continue
  1477. }
  1478. if _, ok := pvMap[key]; !ok {
  1479. log.Warnf("CostModel.ComputeAllocation: pv bytes result for missing pv: %s", err)
  1480. continue
  1481. }
  1482. pvMap[key].Bytes = res.Values[0].Value
  1483. }
  1484. }
  1485. func buildPVCMap(resolution time.Duration, pvcMap map[pvcKey]*pvc, pvMap map[pvKey]*pv, resPVCInfo []*prom.QueryResult) {
  1486. for _, res := range resPVCInfo {
  1487. cluster, err := res.GetString(env.GetPromClusterLabel())
  1488. if err != nil {
  1489. cluster = env.GetClusterID()
  1490. }
  1491. values, err := res.GetStrings("persistentvolumeclaim", "storageclass", "volumename", "namespace")
  1492. if err != nil {
  1493. log.DedupedWarningf(10, "CostModel.ComputeAllocation: pvc info query result missing field: %s", err)
  1494. continue
  1495. }
  1496. namespace := values["namespace"]
  1497. name := values["persistentvolumeclaim"]
  1498. volume := values["volumename"]
  1499. storageClass := values["storageclass"]
  1500. pvKey := newPVKey(cluster, volume)
  1501. pvcKey := newPVCKey(cluster, namespace, name)
  1502. pvcStart, pvcEnd := calculateStartAndEnd(res, resolution)
  1503. if pvcStart.IsZero() || pvcEnd.IsZero() {
  1504. log.Warnf("CostModel.ComputeAllocation: pvc %s has no running time", pvcKey)
  1505. }
  1506. if _, ok := pvMap[pvKey]; !ok {
  1507. continue
  1508. }
  1509. pvMap[pvKey].StorageClass = storageClass
  1510. if _, ok := pvcMap[pvcKey]; !ok {
  1511. pvcMap[pvcKey] = &pvc{}
  1512. }
  1513. pvcMap[pvcKey].Name = name
  1514. pvcMap[pvcKey].Namespace = namespace
  1515. pvcMap[pvcKey].Cluster = cluster
  1516. pvcMap[pvcKey].Volume = pvMap[pvKey]
  1517. pvcMap[pvcKey].Start = pvcStart
  1518. pvcMap[pvcKey].End = pvcEnd
  1519. }
  1520. }
  1521. func applyPVCBytesRequested(pvcMap map[pvcKey]*pvc, resPVCBytesRequested []*prom.QueryResult) {
  1522. for _, res := range resPVCBytesRequested {
  1523. key, err := resultPVCKey(res, env.GetPromClusterLabel(), "namespace", "persistentvolumeclaim")
  1524. if err != nil {
  1525. continue
  1526. }
  1527. if _, ok := pvcMap[key]; !ok {
  1528. continue
  1529. }
  1530. pvcMap[key].Bytes = res.Values[0].Value
  1531. }
  1532. }
  1533. 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) {
  1534. for _, res := range resPodPVCAllocation {
  1535. cluster, err := res.GetString(env.GetPromClusterLabel())
  1536. if err != nil {
  1537. cluster = env.GetClusterID()
  1538. }
  1539. values, err := res.GetStrings("persistentvolume", "persistentvolumeclaim", "pod", "namespace")
  1540. if err != nil {
  1541. log.DedupedWarningf(5, "CostModel.ComputeAllocation: pvc allocation query result missing field: %s", err)
  1542. continue
  1543. }
  1544. namespace := values["namespace"]
  1545. pod := values["pod"]
  1546. name := values["persistentvolumeclaim"]
  1547. volume := values["persistentvolume"]
  1548. key := newPodKey(cluster, namespace, pod)
  1549. pvKey := newPVKey(cluster, volume)
  1550. pvcKey := newPVCKey(cluster, namespace, name)
  1551. var keys []podKey
  1552. if ingestPodUID {
  1553. if uidKeys, ok := podUIDKeyMap[key]; ok {
  1554. keys = append(keys, uidKeys...)
  1555. }
  1556. } else {
  1557. keys = []podKey{key}
  1558. }
  1559. for _, key := range keys {
  1560. if _, ok := pvMap[pvKey]; !ok {
  1561. log.DedupedWarningf(5, "CostModel.ComputeAllocation: pv missing for pvc allocation query result: %s", pvKey)
  1562. continue
  1563. }
  1564. if _, ok := podPVCMap[key]; !ok {
  1565. podPVCMap[key] = []*pvc{}
  1566. }
  1567. pvc, ok := pvcMap[pvcKey]
  1568. if !ok {
  1569. log.DedupedWarningf(5, "CostModel.ComputeAllocation: pvc missing for pvc allocation query: %s", pvcKey)
  1570. continue
  1571. }
  1572. if pod, ok := podMap[key]; !ok || len(pod.Allocations) <= 0 {
  1573. log.DedupedWarningf(10, "CostModel.ComputeAllocation: pvc %s for missing pod %s", pvcKey, key)
  1574. continue
  1575. }
  1576. pvc.Mounted = true
  1577. podPVCMap[key] = append(podPVCMap[key], pvc)
  1578. }
  1579. }
  1580. }
  1581. func applyPVCsToPods(window kubecost.Window, podMap map[podKey]*pod, podPVCMap map[podKey][]*pvc, pvcMap map[pvcKey]*pvc) {
  1582. // Because PVCs can be shared among pods, the respective pv cost
  1583. // needs to be evenly distributed to those pods based on time
  1584. // running, as well as the amount of time the pvc was shared.
  1585. // Build a relation between every pvc to the pods that mount it
  1586. // and a window representing the interval during which they
  1587. // were associated.
  1588. pvcPodWindowMap := make(map[pvcKey]map[podKey]kubecost.Window)
  1589. for thisPodKey, thisPod := range podMap {
  1590. if pvcs, ok := podPVCMap[thisPodKey]; ok {
  1591. for _, thisPVC := range pvcs {
  1592. // Determine the (start, end) of the relationship between the
  1593. // given pvc and the associated Allocation so that a precise
  1594. // number of hours can be used to compute cumulative cost.
  1595. s, e := thisPod.Start, thisPod.End
  1596. if thisPVC.Start.After(thisPod.Start) {
  1597. s = thisPVC.Start
  1598. }
  1599. if thisPVC.End.Before(thisPod.End) {
  1600. e = thisPVC.End
  1601. }
  1602. thisPVCKey := thisPVC.key()
  1603. if pvcPodWindowMap[thisPVCKey] == nil {
  1604. pvcPodWindowMap[thisPVCKey] = make(map[podKey]kubecost.Window)
  1605. }
  1606. pvcPodWindowMap[thisPVCKey][thisPodKey] = kubecost.NewWindow(&s, &e)
  1607. }
  1608. }
  1609. }
  1610. for thisPVCKey, podWindowMap := range pvcPodWindowMap {
  1611. // Build out a pv price coefficient for each pod with a pvc. Each
  1612. // pvc-pod relation needs a coefficient which modifies the pv cost
  1613. // such that pv costs can be shared between all pods using that pvc.
  1614. // Get single-point intervals from alloc-pvc relation windows.
  1615. intervals := getIntervalPointsFromWindows(podWindowMap)
  1616. pvc, ok := pvcMap[thisPVCKey]
  1617. if !ok {
  1618. log.DedupedWarningf(5, "Missing pvc with key %s", thisPVCKey)
  1619. continue
  1620. }
  1621. // Determine coefficients for each pvc-pod relation.
  1622. sharedPVCCostCoefficients := getPVCCostCoefficients(intervals, pvc)
  1623. // Distribute pvc costs to Allocations
  1624. for thisPodKey, coeffComponents := range sharedPVCCostCoefficients {
  1625. pod, ok2 := podMap[thisPodKey]
  1626. // If pod does not exist or the pod does not have any allocations
  1627. // get unmounted pod for cluster
  1628. if !ok2 || len(pod.Allocations) == 0 {
  1629. // Get namespace unmounted pod, as pvc will have a namespace
  1630. pod = getUnmountedPodForNamespace(window, podMap, pvc.Cluster, pvc.Namespace)
  1631. }
  1632. for _, alloc := range pod.Allocations {
  1633. s, e := pod.Start, pod.End
  1634. minutes := e.Sub(s).Minutes()
  1635. hrs := minutes / 60.0
  1636. gib := pvc.Bytes / 1024 / 1024 / 1024
  1637. cost := pvc.Volume.CostPerGiBHour * gib * hrs
  1638. byteHours := pvc.Bytes * hrs
  1639. coef := getCoefficientFromComponents(coeffComponents)
  1640. // Apply the size and cost of the pv to the allocation, each
  1641. // weighted by count (i.e. the number of containers in the pod)
  1642. // record the amount of total PVBytes Hours attributable to a given pv
  1643. if alloc.PVs == nil {
  1644. alloc.PVs = kubecost.PVAllocations{}
  1645. }
  1646. pvKey := kubecost.PVKey{
  1647. Cluster: pvc.Volume.Cluster,
  1648. Name: pvc.Volume.Name,
  1649. }
  1650. // Both Cost and byteHours should be multiplied by the coef and divided by count
  1651. // so that you if all allocations with a given pv key are summed the result of those
  1652. // would be equal to the values of the original pv
  1653. count := float64(len(pod.Allocations))
  1654. alloc.PVs[pvKey] = &kubecost.PVAllocation{
  1655. ByteHours: byteHours * coef / count,
  1656. Cost: cost * coef / count,
  1657. }
  1658. }
  1659. }
  1660. }
  1661. }
  1662. func applyUnmountedPVs(window kubecost.Window, podMap map[podKey]*pod, pvMap map[pvKey]*pv, pvcMap map[pvcKey]*pvc) {
  1663. for _, pv := range pvMap {
  1664. mounted := false
  1665. for _, pvc := range pvcMap {
  1666. if pvc.Volume == nil {
  1667. continue
  1668. }
  1669. if pvc.Volume == pv {
  1670. mounted = true
  1671. break
  1672. }
  1673. }
  1674. if !mounted {
  1675. // a pv without a pvc will not have a namespace, so get the cluster unmounted pod
  1676. pod := getUnmountedPodForCluster(window, podMap, pv.Cluster)
  1677. // Calculate pv Cost
  1678. // Unmounted pv should have correct keyso it can still reconcile
  1679. thisPVKey := kubecost.PVKey{
  1680. Cluster: pv.Cluster,
  1681. Name: pv.Name,
  1682. }
  1683. gib := pv.Bytes / 1024 / 1024 / 1024
  1684. hrs := pv.minutes() / 60.0
  1685. cost := pv.CostPerGiBHour * gib * hrs
  1686. unmountedPVs := kubecost.PVAllocations{
  1687. thisPVKey: {
  1688. ByteHours: pv.Bytes * hrs,
  1689. Cost: cost,
  1690. },
  1691. }
  1692. pod.Allocations[kubecost.UnmountedSuffix].PVs = pod.Allocations[kubecost.UnmountedSuffix].PVs.Add(unmountedPVs)
  1693. }
  1694. }
  1695. }
  1696. func applyUnmountedPVCs(window kubecost.Window, podMap map[podKey]*pod, pvcMap map[pvcKey]*pvc) {
  1697. for _, pvc := range pvcMap {
  1698. if !pvc.Mounted && pvc.Volume != nil {
  1699. // Get namespace unmounted pod, as pvc will have a namespace
  1700. pod := getUnmountedPodForNamespace(window, podMap, pvc.Cluster, pvc.Namespace)
  1701. // Calculate pv Cost
  1702. // Unmounted pv should have correct key so it can still reconcile
  1703. thisPVKey := kubecost.PVKey{
  1704. Cluster: pvc.Volume.Cluster,
  1705. Name: pvc.Volume.Name,
  1706. }
  1707. // Use the Volume Bytes here because pvc bytes could be different,
  1708. // however the pv bytes are what are going to determine cost
  1709. gib := pvc.Volume.Bytes / 1024 / 1024 / 1024
  1710. hrs := pvc.Volume.minutes() / 60.0
  1711. cost := pvc.Volume.CostPerGiBHour * gib * hrs
  1712. unmountedPVs := kubecost.PVAllocations{
  1713. thisPVKey: {
  1714. ByteHours: pvc.Volume.Bytes * hrs,
  1715. Cost: cost,
  1716. },
  1717. }
  1718. pod.Allocations[kubecost.UnmountedSuffix].PVs = pod.Allocations[kubecost.UnmountedSuffix].PVs.Add(unmountedPVs)
  1719. }
  1720. }
  1721. }
  1722. /* Helper Helpers */
  1723. // getUnmountedPodForCluster retrieve the unmounted pod for a cluster and create it if it does not exist
  1724. func getUnmountedPodForCluster(window kubecost.Window, podMap map[podKey]*pod, cluster string) *pod {
  1725. container := kubecost.UnmountedSuffix
  1726. podName := kubecost.UnmountedSuffix
  1727. namespace := kubecost.UnmountedSuffix
  1728. node := ""
  1729. thisPodKey := getUnmountedPodKey(cluster)
  1730. // Initialize pod and container if they do not already exist
  1731. thisPod, ok := podMap[thisPodKey]
  1732. if !ok {
  1733. thisPod = &pod{
  1734. Window: window.Clone(),
  1735. Start: *window.Start(),
  1736. End: *window.End(),
  1737. Key: thisPodKey,
  1738. Allocations: map[string]*kubecost.Allocation{},
  1739. }
  1740. thisPod.appendContainer(container)
  1741. thisPod.Allocations[container].Properties.Cluster = cluster
  1742. thisPod.Allocations[container].Properties.Node = node
  1743. thisPod.Allocations[container].Properties.Namespace = namespace
  1744. thisPod.Allocations[container].Properties.Pod = podName
  1745. thisPod.Allocations[container].Properties.Container = container
  1746. thisPod.Node = node
  1747. podMap[thisPodKey] = thisPod
  1748. }
  1749. return thisPod
  1750. }
  1751. // getUnmountedPodForNamespace is as getUnmountedPodForCluster, but keys allocation property pod/namespace field off namespace
  1752. // This creates or adds allocations to an unmounted pod in the specified namespace, rather than in __unmounted__
  1753. func getUnmountedPodForNamespace(window kubecost.Window, podMap map[podKey]*pod, cluster string, namespace string) *pod {
  1754. container := kubecost.UnmountedSuffix
  1755. podName := fmt.Sprintf("%s-unmounted-pvcs", namespace)
  1756. node := ""
  1757. thisPodKey := newPodKey(cluster, namespace, podName)
  1758. // Initialize pod and container if they do not already exist
  1759. thisPod, ok := podMap[thisPodKey]
  1760. if !ok {
  1761. thisPod = &pod{
  1762. Window: window.Clone(),
  1763. Start: *window.Start(),
  1764. End: *window.End(),
  1765. Key: thisPodKey,
  1766. Allocations: map[string]*kubecost.Allocation{},
  1767. }
  1768. thisPod.appendContainer(container)
  1769. thisPod.Allocations[container].Properties.Cluster = cluster
  1770. thisPod.Allocations[container].Properties.Node = node
  1771. thisPod.Allocations[container].Properties.Namespace = namespace
  1772. thisPod.Allocations[container].Properties.Pod = podName
  1773. thisPod.Allocations[container].Properties.Container = container
  1774. thisPod.Node = node
  1775. podMap[thisPodKey] = thisPod
  1776. }
  1777. return thisPod
  1778. }
  1779. func calculateStartAndEnd(result *prom.QueryResult, resolution time.Duration) (time.Time, time.Time) {
  1780. s := time.Unix(int64(result.Values[0].Timestamp), 0).UTC()
  1781. // subtract resolution from start time to cover full time period
  1782. s = s.Add(-resolution)
  1783. e := time.Unix(int64(result.Values[len(result.Values)-1].Timestamp), 0).UTC()
  1784. return s, e
  1785. }
  1786. // 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
  1787. // 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.
  1788. func calculateStartEndFromIsRunning(result *prom.QueryResult, resolution time.Duration, window kubecost.Window) (time.Time, time.Time) {
  1789. // start and end are the timestamps of the first and last
  1790. // minutes the pod was running, respectively. We subtract one resolution
  1791. // from start because this point will actually represent the end
  1792. // of the first minute. We don't subtract from end because it
  1793. // already represents the end of the last minute.
  1794. var start, end time.Time
  1795. startAdjustmentCoeff, endAdjustmentCoeff := 1.0, 1.0
  1796. for _, datum := range result.Values {
  1797. t := time.Unix(int64(datum.Timestamp), 0)
  1798. if start.IsZero() && datum.Value > 0 && window.Contains(t) {
  1799. // Set the start timestamp to the earliest non-zero timestamp
  1800. start = t
  1801. // Record adjustment coefficient, i.e. the portion of the start
  1802. // timestamp to "ignore". That is, sometimes the value will be
  1803. // 0.5, meaning that we should discount the time running by
  1804. // half of the resolution the timestamp stands for.
  1805. startAdjustmentCoeff = (1.0 - datum.Value)
  1806. }
  1807. if datum.Value > 0 && window.Contains(t) {
  1808. // Set the end timestamp to the latest non-zero timestamp
  1809. end = t
  1810. // Record adjustment coefficient, i.e. the portion of the end
  1811. // timestamp to "ignore". (See explanation above for start.)
  1812. endAdjustmentCoeff = (1.0 - datum.Value)
  1813. }
  1814. }
  1815. // Do not attempt to adjust start if it is zero
  1816. if !start.IsZero() {
  1817. // Adjust timestamps according to the resolution and the adjustment
  1818. // coefficients, as described above. That is, count the start timestamp
  1819. // from the beginning of the resolution, not the end. Then "reduce" the
  1820. // start and end by the correct amount, in the case that the "running"
  1821. // value of the first or last timestamp was not a full 1.0.
  1822. start = start.Add(-resolution)
  1823. // Note: the *100 and /100 are necessary because Duration is an int, so
  1824. // 0.5, for instance, will be truncated, resulting in no adjustment.
  1825. start = start.Add(time.Duration(startAdjustmentCoeff*100) * resolution / time.Duration(100))
  1826. end = end.Add(-time.Duration(endAdjustmentCoeff*100) * resolution / time.Duration(100))
  1827. // Ensure that the start is always within the window, adjusting
  1828. // for the occasions where start falls 1m before the query window.
  1829. // NOTE: window here will always be closed (so no need to nil check
  1830. // "start").
  1831. // TODO:CLEANUP revisit query methodology to figure out why this is
  1832. // happening on occasion
  1833. if start.Before(*window.Start()) {
  1834. start = *window.Start()
  1835. }
  1836. }
  1837. // do not attempt to adjust end if it is zero
  1838. if !end.IsZero() {
  1839. // If there is only one point with a value <= 0.5 that the start and
  1840. // end timestamps both share, then we will enter this case because at
  1841. // least half of a resolution will be subtracted from both the start
  1842. // and the end. If that is the case, then add back half of each side
  1843. // so that the pod is said to run for half a resolution total.
  1844. // e.g. For resolution 1m and a value of 0.5 at one timestamp, we'll
  1845. // end up with end == start and each coeff == 0.5. In
  1846. // that case, add 0.25m to each side, resulting in 0.5m duration.
  1847. if !end.After(start) {
  1848. start = start.Add(-time.Duration(50*startAdjustmentCoeff) * resolution / time.Duration(100))
  1849. end = end.Add(time.Duration(50*endAdjustmentCoeff) * resolution / time.Duration(100))
  1850. }
  1851. // Ensure that the allocEnf is always within the window, adjusting
  1852. // for the occasions where end falls 1m after the query window. This
  1853. // has not ever happened, but is symmetrical with the start check
  1854. // above.
  1855. // NOTE: window here will always be closed (so no need to nil check
  1856. // "end").
  1857. // TODO:CLEANUP revisit query methodology to figure out why this is
  1858. // happening on occasion
  1859. if end.After(*window.End()) {
  1860. end = *window.End()
  1861. }
  1862. }
  1863. return start, end
  1864. }