allocation_helpers.go 78 KB

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