allocation_helpers.go 74 KB

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