allocation_helpers.go 73 KB

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