allocation_helpers.go 76 KB

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