allocation_helpers.go 75 KB

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