allocation_helpers.go 67 KB

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