allocation_helpers.go 63 KB

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