allocation_helpers.go 76 KB

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