costmodel.go 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659
  1. package costmodel
  2. import (
  3. "errors"
  4. "fmt"
  5. "math"
  6. "regexp"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/opencost/opencost/core/pkg/clusters"
  11. "github.com/opencost/opencost/core/pkg/log"
  12. "github.com/opencost/opencost/core/pkg/opencost"
  13. "github.com/opencost/opencost/core/pkg/util"
  14. "github.com/opencost/opencost/core/pkg/util/promutil"
  15. costAnalyzerCloud "github.com/opencost/opencost/pkg/cloud/models"
  16. "github.com/opencost/opencost/pkg/clustercache"
  17. "github.com/opencost/opencost/pkg/env"
  18. "github.com/opencost/opencost/pkg/prom"
  19. prometheus "github.com/prometheus/client_golang/api"
  20. prometheusClient "github.com/prometheus/client_golang/api"
  21. v1 "k8s.io/api/core/v1"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/apimachinery/pkg/labels"
  24. "golang.org/x/sync/singleflight"
  25. )
  26. const (
  27. statusAPIError = 422
  28. profileThreshold = 1000 * 1000 * 1000 // 1s (in ns)
  29. unmountedPVsContainer = "unmounted-pvs"
  30. apiPrefix = "/api/v1"
  31. epAlertManagers = apiPrefix + "/alertmanagers"
  32. epLabelValues = apiPrefix + "/label/:name/values"
  33. epSeries = apiPrefix + "/series"
  34. epTargets = apiPrefix + "/targets"
  35. epSnapshot = apiPrefix + "/admin/tsdb/snapshot"
  36. epDeleteSeries = apiPrefix + "/admin/tsdb/delete_series"
  37. epCleanTombstones = apiPrefix + "/admin/tsdb/clean_tombstones"
  38. epConfig = apiPrefix + "/status/config"
  39. epFlags = apiPrefix + "/status/flags"
  40. )
  41. // isCron matches a CronJob name and captures the non-timestamp name
  42. //
  43. // We support either a 10 character timestamp OR an 8 character timestamp
  44. // because batch/v1beta1 CronJobs creates Jobs with 10 character timestamps
  45. // and batch/v1 CronJobs create Jobs with 8 character timestamps.
  46. var isCron = regexp.MustCompile(`^(.+)-(\d{10}|\d{8})$`)
  47. type CostModel struct {
  48. Cache clustercache.ClusterCache
  49. ClusterMap clusters.ClusterMap
  50. MaxPrometheusQueryDuration time.Duration
  51. RequestGroup *singleflight.Group
  52. ScrapeInterval time.Duration
  53. PrometheusClient prometheus.Client
  54. Provider costAnalyzerCloud.Provider
  55. pricingMetadata *costAnalyzerCloud.PricingMatchMetadata
  56. }
  57. func NewCostModel(client prometheus.Client, provider costAnalyzerCloud.Provider, cache clustercache.ClusterCache, clusterMap clusters.ClusterMap, scrapeInterval time.Duration) *CostModel {
  58. // request grouping to prevent over-requesting the same data prior to caching
  59. requestGroup := new(singleflight.Group)
  60. return &CostModel{
  61. Cache: cache,
  62. ClusterMap: clusterMap,
  63. MaxPrometheusQueryDuration: env.GetETLMaxPrometheusQueryDuration(),
  64. PrometheusClient: client,
  65. Provider: provider,
  66. RequestGroup: requestGroup,
  67. ScrapeInterval: scrapeInterval,
  68. }
  69. }
  70. type CostData struct {
  71. Name string `json:"name,omitempty"`
  72. PodName string `json:"podName,omitempty"`
  73. NodeName string `json:"nodeName,omitempty"`
  74. NodeData *costAnalyzerCloud.Node `json:"node,omitempty"`
  75. Namespace string `json:"namespace,omitempty"`
  76. Deployments []string `json:"deployments,omitempty"`
  77. Services []string `json:"services,omitempty"`
  78. Daemonsets []string `json:"daemonsets,omitempty"`
  79. Statefulsets []string `json:"statefulsets,omitempty"`
  80. Jobs []string `json:"jobs,omitempty"`
  81. RAMReq []*util.Vector `json:"ramreq,omitempty"`
  82. RAMUsed []*util.Vector `json:"ramused,omitempty"`
  83. RAMAllocation []*util.Vector `json:"ramallocated,omitempty"`
  84. CPUReq []*util.Vector `json:"cpureq,omitempty"`
  85. CPUUsed []*util.Vector `json:"cpuused,omitempty"`
  86. CPUAllocation []*util.Vector `json:"cpuallocated,omitempty"`
  87. GPUReq []*util.Vector `json:"gpureq,omitempty"`
  88. PVCData []*PersistentVolumeClaimData `json:"pvcData,omitempty"`
  89. NetworkData []*util.Vector `json:"network,omitempty"`
  90. Annotations map[string]string `json:"annotations,omitempty"`
  91. Labels map[string]string `json:"labels,omitempty"`
  92. NamespaceLabels map[string]string `json:"namespaceLabels,omitempty"`
  93. ClusterID string `json:"clusterId"`
  94. ClusterName string `json:"clusterName"`
  95. }
  96. func (cd *CostData) String() string {
  97. return fmt.Sprintf("\n\tName: %s; PodName: %s, NodeName: %s\n\tNamespace: %s\n\tDeployments: %s\n\tServices: %s\n\tCPU (req, used, alloc): %d, %d, %d\n\tRAM (req, used, alloc): %d, %d, %d",
  98. cd.Name, cd.PodName, cd.NodeName, cd.Namespace, strings.Join(cd.Deployments, ", "), strings.Join(cd.Services, ", "),
  99. len(cd.CPUReq), len(cd.CPUUsed), len(cd.CPUAllocation),
  100. len(cd.RAMReq), len(cd.RAMUsed), len(cd.RAMAllocation))
  101. }
  102. func (cd *CostData) GetController() (name string, kind string, hasController bool) {
  103. hasController = false
  104. if len(cd.Deployments) > 0 {
  105. name = cd.Deployments[0]
  106. kind = "deployment"
  107. hasController = true
  108. } else if len(cd.Statefulsets) > 0 {
  109. name = cd.Statefulsets[0]
  110. kind = "statefulset"
  111. hasController = true
  112. } else if len(cd.Daemonsets) > 0 {
  113. name = cd.Daemonsets[0]
  114. kind = "daemonset"
  115. hasController = true
  116. } else if len(cd.Jobs) > 0 {
  117. name = cd.Jobs[0]
  118. kind = "job"
  119. hasController = true
  120. match := isCron.FindStringSubmatch(name)
  121. if match != nil {
  122. name = match[1]
  123. }
  124. }
  125. return name, kind, hasController
  126. }
  127. const (
  128. queryRAMRequestsStr = `avg(
  129. label_replace(
  130. label_replace(
  131. sum_over_time(kube_pod_container_resource_requests{resource="memory", unit="byte", container!="",container!="POD", node!="", %s}[%s] %s)
  132. , "container_name","$1","container","(.+)"
  133. ), "pod_name","$1","pod","(.+)"
  134. )
  135. ) by (namespace,container_name,pod_name,node,%s)`
  136. queryRAMUsageStr = `avg(
  137. label_replace(
  138. label_replace(
  139. label_replace(
  140. sum_over_time(container_memory_working_set_bytes{container!="", container!="POD", instance!="", %s}[%s] %s), "node", "$1", "instance", "(.+)"
  141. ), "container_name", "$1", "container", "(.+)"
  142. ), "pod_name", "$1", "pod", "(.+)"
  143. )
  144. ) by (namespace, container_name, pod_name, node, %s)`
  145. queryCPURequestsStr = `avg(
  146. label_replace(
  147. label_replace(
  148. sum_over_time(kube_pod_container_resource_requests{resource="cpu", unit="core", container!="",container!="POD", node!="", %s}[%s] %s)
  149. , "container_name","$1","container","(.+)"
  150. ), "pod_name","$1","pod","(.+)"
  151. )
  152. ) by (namespace,container_name,pod_name,node,%s)`
  153. queryCPUUsageStr = `avg(
  154. label_replace(
  155. label_replace(
  156. label_replace(
  157. rate(
  158. container_cpu_usage_seconds_total{container!="", container!="POD", instance!="", %s}[%s] %s
  159. ), "node", "$1", "instance", "(.+)"
  160. ), "container_name", "$1", "container", "(.+)"
  161. ), "pod_name", "$1", "pod", "(.+)"
  162. )
  163. ) by (namespace, container_name, pod_name, node, %s)`
  164. queryGPURequestsStr = `avg(
  165. label_replace(
  166. label_replace(
  167. sum_over_time(kube_pod_container_resource_requests{resource="nvidia_com_gpu", container!="",container!="POD", node!="", %s}[%s] %s),
  168. "container_name","$1","container","(.+)"
  169. ), "pod_name","$1","pod","(.+)"
  170. )
  171. ) by (namespace,container_name,pod_name,node,%s)`
  172. queryPVRequestsStr = `avg(avg(kube_persistentvolumeclaim_info{volumename != "", %s}) by (persistentvolumeclaim, storageclass, namespace, volumename, %s, kubernetes_node)
  173. *
  174. on (persistentvolumeclaim, namespace, %s, kubernetes_node) group_right(storageclass, volumename)
  175. sum(kube_persistentvolumeclaim_resource_requests_storage_bytes{%s}) by (persistentvolumeclaim, namespace, %s, kubernetes_node, kubernetes_name)) by (persistentvolumeclaim, storageclass, namespace, %s, volumename, kubernetes_node)`
  176. // queryRAMAllocationByteHours yields the total byte-hour RAM allocation over the given
  177. // window, aggregated by container.
  178. // [line 3] sum_over_time(each byte) = [byte*scrape] by metric
  179. // [line 4] (scalar(avg(prometheus_target_interval_length_seconds)) = [seconds/scrape] / 60 / 60 = [hours/scrape] by container
  180. // [lines 2,4] sum(") by unique container key and multiply [byte*scrape] * [hours/scrape] for byte*hours
  181. // [lines 1,5] relabeling
  182. queryRAMAllocationByteHours = `
  183. label_replace(label_replace(
  184. sum(
  185. sum_over_time(container_memory_allocation_bytes{container!="",container!="POD", node!="", %s}[%s])
  186. ) by (namespace,container,pod,node,%s) * %f / 60 / 60
  187. , "container_name","$1","container","(.+)"), "pod_name","$1","pod","(.+)")`
  188. // queryCPUAllocationVCPUHours yields the total VCPU-hour CPU allocation over the given
  189. // window, aggregated by container.
  190. // [line 3] sum_over_time(each VCPU*mins in window) = [VCPU*scrape] by metric
  191. // [line 4] (scalar(avg(prometheus_target_interval_length_seconds)) = [seconds/scrape] / 60 / 60 = [hours/scrape] by container
  192. // [lines 2,4] sum(") by unique container key and multiply [VCPU*scrape] * [hours/scrape] for VCPU*hours
  193. // [lines 1,5] relabeling
  194. queryCPUAllocationVCPUHours = `
  195. label_replace(label_replace(
  196. sum(
  197. sum_over_time(container_cpu_allocation{container!="",container!="POD", node!="", %s}[%s])
  198. ) by (namespace,container,pod,node,%s) * %f / 60 / 60
  199. , "container_name","$1","container","(.+)"), "pod_name","$1","pod","(.+)")`
  200. // queryPVCAllocationFmt yields the total byte-hour PVC allocation over the given window.
  201. // sum_over_time(each byte) = [byte*scrape] by metric *(scalar(avg(prometheus_target_interval_length_seconds)) = [seconds/scrape] / 60 / 60 = [hours/scrape] by pod
  202. queryPVCAllocationFmt = `sum(sum_over_time(pod_pvc_allocation{%s}[%s])) by (%s, namespace, pod, persistentvolume, persistentvolumeclaim) * %f/60/60`
  203. queryPVHourlyCostFmt = `avg_over_time(pv_hourly_cost{%s}[%s])`
  204. queryNSLabels = `avg_over_time(kube_namespace_labels{%s}[%s])`
  205. queryPodLabels = `avg_over_time(kube_pod_labels{%s}[%s])`
  206. queryNSAnnotations = `avg_over_time(kube_namespace_annotations{%s}[%s])`
  207. queryPodAnnotations = `avg_over_time(kube_pod_annotations{%s}[%s])`
  208. queryDeploymentLabels = `avg_over_time(deployment_match_labels{%s}[%s])`
  209. queryStatefulsetLabels = `avg_over_time(statefulSet_match_labels{%s}[%s])`
  210. queryPodDaemonsets = `sum(kube_pod_owner{owner_kind="DaemonSet", %s}) by (namespace,pod,owner_name,%s)`
  211. queryPodJobs = `sum(kube_pod_owner{owner_kind="Job", %s}) by (namespace,pod,owner_name,%s)`
  212. queryServiceLabels = `avg_over_time(service_selector_labels{%s}[%s])`
  213. queryZoneNetworkUsage = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="false", sameZone="false", sameRegion="true", %s}[%s] %s)) by (namespace,pod_name,%s) / 1024 / 1024 / 1024`
  214. queryRegionNetworkUsage = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="false", sameZone="false", sameRegion="false", %s}[%s] %s)) by (namespace,pod_name,%s) / 1024 / 1024 / 1024`
  215. queryInternetNetworkUsage = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="true", %s}[%s] %s)) by (namespace,pod_name,%s) / 1024 / 1024 / 1024`
  216. normalizationStr = `max(count_over_time(kube_pod_container_resource_requests{resource="memory", unit="byte", %s}[%s] %s))`
  217. )
  218. func (cm *CostModel) ComputeCostData(cli prometheusClient.Client, cp costAnalyzerCloud.Provider, window string, offset string, filterNamespace string) (map[string]*CostData, error) {
  219. queryRAMUsage := fmt.Sprintf(queryRAMUsageStr, env.GetPromClusterFilter(), window, offset, env.GetPromClusterLabel())
  220. queryCPUUsage := fmt.Sprintf(queryCPUUsageStr, env.GetPromClusterFilter(), window, offset, env.GetPromClusterLabel())
  221. queryNetZoneRequests := fmt.Sprintf(queryZoneNetworkUsage, env.GetPromClusterFilter(), window, "", env.GetPromClusterLabel())
  222. queryNetRegionRequests := fmt.Sprintf(queryRegionNetworkUsage, env.GetPromClusterFilter(), window, "", env.GetPromClusterLabel())
  223. queryNetInternetRequests := fmt.Sprintf(queryInternetNetworkUsage, env.GetPromClusterFilter(), window, "", env.GetPromClusterLabel())
  224. queryNormalization := fmt.Sprintf(normalizationStr, env.GetPromClusterFilter(), window, offset)
  225. // Cluster ID is specific to the source cluster
  226. clusterID := env.GetClusterID()
  227. // Submit all Prometheus queries asynchronously
  228. ctx := prom.NewNamedContext(cli, prom.ComputeCostDataContextName)
  229. resChRAMUsage := ctx.Query(queryRAMUsage)
  230. resChCPUUsage := ctx.Query(queryCPUUsage)
  231. resChNetZoneRequests := ctx.Query(queryNetZoneRequests)
  232. resChNetRegionRequests := ctx.Query(queryNetRegionRequests)
  233. resChNetInternetRequests := ctx.Query(queryNetInternetRequests)
  234. resChNormalization := ctx.Query(queryNormalization)
  235. // Pull pod information from k8s API
  236. podlist := cm.Cache.GetAllPods()
  237. podDeploymentsMapping, err := getPodDeployments(cm.Cache, podlist, clusterID)
  238. if err != nil {
  239. return nil, err
  240. }
  241. podServicesMapping, err := getPodServices(cm.Cache, podlist, clusterID)
  242. if err != nil {
  243. return nil, err
  244. }
  245. namespaceLabelsMapping, err := getNamespaceLabels(cm.Cache, clusterID)
  246. if err != nil {
  247. return nil, err
  248. }
  249. namespaceAnnotationsMapping, err := getNamespaceAnnotations(cm.Cache, clusterID)
  250. if err != nil {
  251. return nil, err
  252. }
  253. // Process Prometheus query results. Handle errors using ctx.Errors.
  254. resRAMUsage, _ := resChRAMUsage.Await()
  255. resCPUUsage, _ := resChCPUUsage.Await()
  256. resNetZoneRequests, _ := resChNetZoneRequests.Await()
  257. resNetRegionRequests, _ := resChNetRegionRequests.Await()
  258. resNetInternetRequests, _ := resChNetInternetRequests.Await()
  259. resNormalization, _ := resChNormalization.Await()
  260. // NOTE: The way we currently handle errors and warnings only early returns if there is an error. Warnings
  261. // NOTE: will not propagate unless coupled with errors.
  262. if ctx.HasErrors() {
  263. // To keep the context of where the errors are occurring, we log the errors here and pass them the error
  264. // back to the caller. The caller should handle the specific case where error is an ErrorCollection
  265. for _, promErr := range ctx.Errors() {
  266. if promErr.Error != nil {
  267. log.Errorf("ComputeCostData: Request Error: %s", promErr.Error)
  268. }
  269. if promErr.ParseError != nil {
  270. log.Errorf("ComputeCostData: Parsing Error: %s", promErr.ParseError)
  271. }
  272. }
  273. // ErrorCollection is an collection of errors wrapped in a single error implementation
  274. // We opt to not return an error for the sake of running as a pure exporter.
  275. log.Warnf("ComputeCostData: continuing despite prometheus errors: %s", ctx.ErrorCollection().Error())
  276. }
  277. defer measureTime(time.Now(), profileThreshold, "ComputeCostData: Processing Query Data")
  278. normalizationValue, err := getNormalization(resNormalization)
  279. if err != nil {
  280. // We opt to not return an error for the sake of running as a pure exporter.
  281. log.Warnf("ComputeCostData: continuing despite error parsing normalization values from %s: %s", queryNormalization, err.Error())
  282. }
  283. nodes, err := cm.GetNodeCost(cp)
  284. if err != nil {
  285. log.Warnf("GetNodeCost: no node cost model available: " + err.Error())
  286. return nil, err
  287. }
  288. // Unmounted PVs represent the PVs that are not mounted or tied to a volume on a container
  289. unmountedPVs := make(map[string][]*PersistentVolumeClaimData)
  290. pvClaimMapping, err := GetPVInfoLocal(cm.Cache, clusterID)
  291. if err != nil {
  292. log.Warnf("GetPVInfo: unable to get PV data: %s", err.Error())
  293. }
  294. if pvClaimMapping != nil {
  295. err = addPVData(cm.Cache, pvClaimMapping, cp)
  296. if err != nil {
  297. return nil, err
  298. }
  299. // copy claim mappings into zombies, then remove as they're discovered
  300. for k, v := range pvClaimMapping {
  301. unmountedPVs[k] = []*PersistentVolumeClaimData{v}
  302. }
  303. }
  304. networkUsageMap, err := GetNetworkUsageData(resNetZoneRequests, resNetRegionRequests, resNetInternetRequests, clusterID)
  305. if err != nil {
  306. log.Warnf("Unable to get Network Cost Data: %s", err.Error())
  307. networkUsageMap = make(map[string]*NetworkUsageData)
  308. }
  309. containerNameCost := make(map[string]*CostData)
  310. containers := make(map[string]bool)
  311. RAMUsedMap, err := GetContainerMetricVector(resRAMUsage, true, normalizationValue, clusterID)
  312. if err != nil {
  313. return nil, err
  314. }
  315. for key := range RAMUsedMap {
  316. containers[key] = true
  317. }
  318. CPUUsedMap, err := GetContainerMetricVector(resCPUUsage, false, 0, clusterID) // No need to normalize here, as this comes from a counter
  319. if err != nil {
  320. return nil, err
  321. }
  322. for key := range CPUUsedMap {
  323. containers[key] = true
  324. }
  325. currentContainers := make(map[string]v1.Pod)
  326. for _, pod := range podlist {
  327. if pod.Status.Phase != v1.PodRunning {
  328. continue
  329. }
  330. cs, err := NewContainerMetricsFromPod(pod, clusterID)
  331. if err != nil {
  332. return nil, err
  333. }
  334. for _, c := range cs {
  335. containers[c.Key()] = true // captures any containers that existed for a time < a prometheus scrape interval. We currently charge 0 for this but should charge something.
  336. currentContainers[c.Key()] = *pod
  337. }
  338. }
  339. missingNodes := make(map[string]*costAnalyzerCloud.Node)
  340. missingContainers := make(map[string]*CostData)
  341. for key := range containers {
  342. if _, ok := containerNameCost[key]; ok {
  343. continue // because ordering is important for the allocation model (all PV's applied to the first), just dedupe if it's already been added.
  344. }
  345. // The _else_ case for this statement is the case in which the container has been
  346. // deleted so we have usage information but not request information. In that case,
  347. // we return partial data for CPU and RAM: only usage and not requests.
  348. if pod, ok := currentContainers[key]; ok {
  349. podName := pod.GetObjectMeta().GetName()
  350. ns := pod.GetObjectMeta().GetNamespace()
  351. nsLabels := namespaceLabelsMapping[ns+","+clusterID]
  352. podLabels := pod.GetObjectMeta().GetLabels()
  353. if podLabels == nil {
  354. podLabels = make(map[string]string)
  355. }
  356. for k, v := range nsLabels {
  357. if _, ok := podLabels[k]; !ok {
  358. podLabels[k] = v
  359. }
  360. }
  361. nsAnnotations := namespaceAnnotationsMapping[ns+","+clusterID]
  362. podAnnotations := pod.GetObjectMeta().GetAnnotations()
  363. if podAnnotations == nil {
  364. podAnnotations = make(map[string]string)
  365. }
  366. for k, v := range nsAnnotations {
  367. if _, ok := podAnnotations[k]; !ok {
  368. podAnnotations[k] = v
  369. }
  370. }
  371. nodeName := pod.Spec.NodeName
  372. var nodeData *costAnalyzerCloud.Node
  373. if _, ok := nodes[nodeName]; ok {
  374. nodeData = nodes[nodeName]
  375. }
  376. nsKey := ns + "," + clusterID
  377. var podDeployments []string
  378. if _, ok := podDeploymentsMapping[nsKey]; ok {
  379. if ds, ok := podDeploymentsMapping[nsKey][pod.GetObjectMeta().GetName()]; ok {
  380. podDeployments = ds
  381. } else {
  382. podDeployments = []string{}
  383. }
  384. }
  385. var podPVs []*PersistentVolumeClaimData
  386. podClaims := pod.Spec.Volumes
  387. for _, vol := range podClaims {
  388. if vol.PersistentVolumeClaim != nil {
  389. name := vol.PersistentVolumeClaim.ClaimName
  390. key := ns + "," + name + "," + clusterID
  391. if pvClaim, ok := pvClaimMapping[key]; ok {
  392. pvClaim.TimesClaimed++
  393. podPVs = append(podPVs, pvClaim)
  394. // Remove entry from potential unmounted pvs
  395. delete(unmountedPVs, key)
  396. }
  397. }
  398. }
  399. var podNetCosts []*util.Vector
  400. if usage, ok := networkUsageMap[ns+","+podName+","+clusterID]; ok {
  401. netCosts, err := GetNetworkCost(usage, cp)
  402. if err != nil {
  403. log.Debugf("Error pulling network costs: %s", err.Error())
  404. } else {
  405. podNetCosts = netCosts
  406. }
  407. }
  408. var podServices []string
  409. if _, ok := podServicesMapping[nsKey]; ok {
  410. if svcs, ok := podServicesMapping[nsKey][pod.GetObjectMeta().GetName()]; ok {
  411. podServices = svcs
  412. } else {
  413. podServices = []string{}
  414. }
  415. }
  416. for i, container := range pod.Spec.Containers {
  417. containerName := container.Name
  418. // recreate the key and look up data for this container
  419. newKey := NewContainerMetricFromValues(ns, podName, containerName, pod.Spec.NodeName, clusterID).Key()
  420. // k8s.io/apimachinery/pkg/api/resource/amount.go and
  421. // k8s.io/apimachinery/pkg/api/resource/quantity.go for
  422. // details on the "amount" API. See
  423. // https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#resource-types
  424. // for the units of memory and CPU.
  425. ramRequestBytes := container.Resources.Requests.Memory().Value()
  426. // Because information on container RAM & CPU requests isn't
  427. // coming from Prometheus, it won't have a timestamp associated
  428. // with it. We need to provide a timestamp.
  429. RAMReqV := []*util.Vector{
  430. {
  431. Value: float64(ramRequestBytes),
  432. Timestamp: float64(time.Now().UTC().Unix()),
  433. },
  434. }
  435. // use millicores so we can convert to cores in a float64 format
  436. cpuRequestMilliCores := container.Resources.Requests.Cpu().MilliValue()
  437. CPUReqV := []*util.Vector{
  438. {
  439. Value: float64(cpuRequestMilliCores) / 1000,
  440. Timestamp: float64(time.Now().UTC().Unix()),
  441. },
  442. }
  443. gpuReqCount := 0.0
  444. if g, ok := container.Resources.Requests["nvidia.com/gpu"]; ok {
  445. gpuReqCount = g.AsApproximateFloat64()
  446. } else if g, ok := container.Resources.Limits["nvidia.com/gpu"]; ok {
  447. gpuReqCount = g.AsApproximateFloat64()
  448. } else if g, ok := container.Resources.Requests["k8s.amazonaws.com/vgpu"]; ok {
  449. gpuReqCount = g.AsApproximateFloat64()
  450. } else if g, ok := container.Resources.Limits["k8s.amazonaws.com/vgpu"]; ok {
  451. gpuReqCount = g.AsApproximateFloat64()
  452. }
  453. GPUReqV := []*util.Vector{
  454. {
  455. Value: float64(gpuReqCount),
  456. Timestamp: float64(time.Now().UTC().Unix()),
  457. },
  458. }
  459. RAMUsedV, ok := RAMUsedMap[newKey]
  460. if !ok {
  461. log.Debug("no RAM usage for " + newKey)
  462. RAMUsedV = []*util.Vector{{}}
  463. }
  464. CPUUsedV, ok := CPUUsedMap[newKey]
  465. if !ok {
  466. log.Debug("no CPU usage for " + newKey)
  467. CPUUsedV = []*util.Vector{{}}
  468. }
  469. var pvReq []*PersistentVolumeClaimData
  470. var netReq []*util.Vector
  471. if i == 0 { // avoid duplicating by just assigning all claims to the first container.
  472. pvReq = podPVs
  473. netReq = podNetCosts
  474. }
  475. costs := &CostData{
  476. Name: containerName,
  477. PodName: podName,
  478. NodeName: nodeName,
  479. Namespace: ns,
  480. Deployments: podDeployments,
  481. Services: podServices,
  482. Daemonsets: getDaemonsetsOfPod(pod),
  483. Jobs: getJobsOfPod(pod),
  484. Statefulsets: getStatefulSetsOfPod(pod),
  485. NodeData: nodeData,
  486. RAMReq: RAMReqV,
  487. RAMUsed: RAMUsedV,
  488. CPUReq: CPUReqV,
  489. CPUUsed: CPUUsedV,
  490. GPUReq: GPUReqV,
  491. PVCData: pvReq,
  492. NetworkData: netReq,
  493. Annotations: podAnnotations,
  494. Labels: podLabels,
  495. NamespaceLabels: nsLabels,
  496. ClusterID: clusterID,
  497. ClusterName: cm.ClusterMap.NameFor(clusterID),
  498. }
  499. var cpuReq, cpuUse *util.Vector
  500. if len(costs.CPUReq) > 0 {
  501. cpuReq = costs.CPUReq[0]
  502. }
  503. if len(costs.CPUUsed) > 0 {
  504. cpuUse = costs.CPUUsed[0]
  505. }
  506. costs.CPUAllocation = getContainerAllocation(cpuReq, cpuUse, "CPU")
  507. var ramReq, ramUse *util.Vector
  508. if len(costs.RAMReq) > 0 {
  509. ramReq = costs.RAMReq[0]
  510. }
  511. if len(costs.RAMUsed) > 0 {
  512. ramUse = costs.RAMUsed[0]
  513. }
  514. costs.RAMAllocation = getContainerAllocation(ramReq, ramUse, "RAM")
  515. if filterNamespace == "" {
  516. containerNameCost[newKey] = costs
  517. } else if costs.Namespace == filterNamespace {
  518. containerNameCost[newKey] = costs
  519. }
  520. }
  521. } else {
  522. // The container has been deleted. Not all information is sent to prometheus via ksm, so fill out what we can without k8s api
  523. log.Debug("The container " + key + " has been deleted. Calculating allocation but resulting object will be missing data.")
  524. c, err := NewContainerMetricFromKey(key)
  525. if err != nil {
  526. return nil, err
  527. }
  528. // CPU and RAM requests are obtained from the Kubernetes API.
  529. // If this case has been reached, the Kubernetes API will not
  530. // have information about the pod because it no longer exists.
  531. //
  532. // The case where this matters is minimal, mainly in environments
  533. // with very short-lived pods that over-request resources.
  534. RAMReqV := []*util.Vector{{}}
  535. CPUReqV := []*util.Vector{{}}
  536. GPUReqV := []*util.Vector{{}}
  537. RAMUsedV, ok := RAMUsedMap[key]
  538. if !ok {
  539. log.Debug("no RAM usage for " + key)
  540. RAMUsedV = []*util.Vector{{}}
  541. }
  542. CPUUsedV, ok := CPUUsedMap[key]
  543. if !ok {
  544. log.Debug("no CPU usage for " + key)
  545. CPUUsedV = []*util.Vector{{}}
  546. }
  547. node, ok := nodes[c.NodeName]
  548. if !ok {
  549. log.Debugf("Node \"%s\" has been deleted from Kubernetes. Query historical data to get it.", c.NodeName)
  550. if n, ok := missingNodes[c.NodeName]; ok {
  551. node = n
  552. } else {
  553. node = &costAnalyzerCloud.Node{}
  554. missingNodes[c.NodeName] = node
  555. }
  556. }
  557. namespacelabels, _ := namespaceLabelsMapping[c.Namespace+","+c.ClusterID]
  558. namespaceAnnotations, _ := namespaceAnnotationsMapping[c.Namespace+","+c.ClusterID]
  559. costs := &CostData{
  560. Name: c.ContainerName,
  561. PodName: c.PodName,
  562. NodeName: c.NodeName,
  563. NodeData: node,
  564. Namespace: c.Namespace,
  565. RAMReq: RAMReqV,
  566. RAMUsed: RAMUsedV,
  567. CPUReq: CPUReqV,
  568. CPUUsed: CPUUsedV,
  569. GPUReq: GPUReqV,
  570. Annotations: namespaceAnnotations,
  571. NamespaceLabels: namespacelabels,
  572. ClusterID: c.ClusterID,
  573. ClusterName: cm.ClusterMap.NameFor(c.ClusterID),
  574. }
  575. var cpuReq, cpuUse *util.Vector
  576. if len(costs.CPUReq) > 0 {
  577. cpuReq = costs.CPUReq[0]
  578. }
  579. if len(costs.CPUUsed) > 0 {
  580. cpuUse = costs.CPUUsed[0]
  581. }
  582. costs.CPUAllocation = getContainerAllocation(cpuReq, cpuUse, "CPU")
  583. var ramReq, ramUse *util.Vector
  584. if len(costs.RAMReq) > 0 {
  585. ramReq = costs.RAMReq[0]
  586. }
  587. if len(costs.RAMUsed) > 0 {
  588. ramUse = costs.RAMUsed[0]
  589. }
  590. costs.RAMAllocation = getContainerAllocation(ramReq, ramUse, "RAM")
  591. if filterNamespace == "" {
  592. containerNameCost[key] = costs
  593. missingContainers[key] = costs
  594. } else if costs.Namespace == filterNamespace {
  595. containerNameCost[key] = costs
  596. missingContainers[key] = costs
  597. }
  598. }
  599. }
  600. // Use unmounted pvs to create a mapping of "Unmounted-<Namespace>" containers
  601. // to pass along the cost data
  602. unmounted := findUnmountedPVCostData(cm.ClusterMap, unmountedPVs, namespaceLabelsMapping, namespaceAnnotationsMapping)
  603. for k, costs := range unmounted {
  604. log.Debugf("Unmounted PVs in Namespace/ClusterID: %s/%s", costs.Namespace, costs.ClusterID)
  605. if filterNamespace == "" {
  606. containerNameCost[k] = costs
  607. } else if costs.Namespace == filterNamespace {
  608. containerNameCost[k] = costs
  609. }
  610. }
  611. err = findDeletedNodeInfo(cli, missingNodes, window, "")
  612. if err != nil {
  613. log.Errorf("Error fetching historical node data: %s", err.Error())
  614. }
  615. err = findDeletedPodInfo(cli, missingContainers, window)
  616. if err != nil {
  617. log.Errorf("Error fetching historical pod data: %s", err.Error())
  618. }
  619. return containerNameCost, err
  620. }
  621. func findUnmountedPVCostData(clusterMap clusters.ClusterMap, unmountedPVs map[string][]*PersistentVolumeClaimData, namespaceLabelsMapping map[string]map[string]string, namespaceAnnotationsMapping map[string]map[string]string) map[string]*CostData {
  622. costs := make(map[string]*CostData)
  623. if len(unmountedPVs) == 0 {
  624. return costs
  625. }
  626. for k, pv := range unmountedPVs {
  627. keyParts := strings.Split(k, ",")
  628. if len(keyParts) != 3 {
  629. log.Warnf("Unmounted PV used key with incorrect parts: %s", k)
  630. continue
  631. }
  632. ns, _, clusterID := keyParts[0], keyParts[1], keyParts[2]
  633. namespacelabels, _ := namespaceLabelsMapping[ns+","+clusterID]
  634. namespaceAnnotations, _ := namespaceAnnotationsMapping[ns+","+clusterID]
  635. metric := NewContainerMetricFromValues(ns, unmountedPVsContainer, unmountedPVsContainer, "", clusterID)
  636. key := metric.Key()
  637. if costData, ok := costs[key]; !ok {
  638. costs[key] = &CostData{
  639. Name: unmountedPVsContainer,
  640. PodName: unmountedPVsContainer,
  641. NodeName: "",
  642. Annotations: namespaceAnnotations,
  643. Namespace: ns,
  644. NamespaceLabels: namespacelabels,
  645. Labels: namespacelabels,
  646. ClusterID: clusterID,
  647. ClusterName: clusterMap.NameFor(clusterID),
  648. PVCData: pv,
  649. }
  650. } else {
  651. costData.PVCData = append(costData.PVCData, pv...)
  652. }
  653. }
  654. return costs
  655. }
  656. func findDeletedPodInfo(cli prometheusClient.Client, missingContainers map[string]*CostData, window string) error {
  657. if len(missingContainers) > 0 {
  658. queryHistoricalPodLabels := fmt.Sprintf(`kube_pod_labels{%s}[%s]`, env.GetPromClusterFilter(), window)
  659. podLabelsResult, _, err := prom.NewNamedContext(cli, prom.ComputeCostDataContextName).QuerySync(queryHistoricalPodLabels)
  660. if err != nil {
  661. log.Errorf("failed to parse historical pod labels: %s", err.Error())
  662. }
  663. podLabels := make(map[string]map[string]string)
  664. if podLabelsResult != nil {
  665. podLabels, err = parsePodLabels(podLabelsResult)
  666. if err != nil {
  667. log.Errorf("failed to parse historical pod labels: %s", err.Error())
  668. }
  669. }
  670. for key, costData := range missingContainers {
  671. cm, _ := NewContainerMetricFromKey(key)
  672. labels, ok := podLabels[cm.PodName]
  673. if !ok {
  674. labels = make(map[string]string)
  675. }
  676. for k, v := range costData.NamespaceLabels {
  677. labels[k] = v
  678. }
  679. costData.Labels = labels
  680. }
  681. }
  682. return nil
  683. }
  684. func findDeletedNodeInfo(cli prometheusClient.Client, missingNodes map[string]*costAnalyzerCloud.Node, window, offset string) error {
  685. if len(missingNodes) > 0 {
  686. defer measureTime(time.Now(), profileThreshold, "Finding Deleted Node Info")
  687. offsetStr := ""
  688. if offset != "" {
  689. offsetStr = fmt.Sprintf("offset %s", offset)
  690. }
  691. queryHistoricalCPUCost := fmt.Sprintf(`avg(avg_over_time(node_cpu_hourly_cost{%s}[%s] %s)) by (node, instance, %s)`, env.GetPromClusterFilter(), window, offsetStr, env.GetPromClusterLabel())
  692. queryHistoricalRAMCost := fmt.Sprintf(`avg(avg_over_time(node_ram_hourly_cost{%s}[%s] %s)) by (node, instance, %s)`, env.GetPromClusterFilter(), window, offsetStr, env.GetPromClusterLabel())
  693. queryHistoricalGPUCost := fmt.Sprintf(`avg(avg_over_time(node_gpu_hourly_cost{%s}[%s] %s)) by (node, instance, %s)`, env.GetPromClusterFilter(), window, offsetStr, env.GetPromClusterLabel())
  694. ctx := prom.NewNamedContext(cli, prom.ComputeCostDataContextName)
  695. cpuCostResCh := ctx.Query(queryHistoricalCPUCost)
  696. ramCostResCh := ctx.Query(queryHistoricalRAMCost)
  697. gpuCostResCh := ctx.Query(queryHistoricalGPUCost)
  698. cpuCostRes, _ := cpuCostResCh.Await()
  699. ramCostRes, _ := ramCostResCh.Await()
  700. gpuCostRes, _ := gpuCostResCh.Await()
  701. if ctx.HasErrors() {
  702. return ctx.ErrorCollection()
  703. }
  704. cpuCosts, err := getCost(cpuCostRes)
  705. if err != nil {
  706. return err
  707. }
  708. ramCosts, err := getCost(ramCostRes)
  709. if err != nil {
  710. return err
  711. }
  712. gpuCosts, err := getCost(gpuCostRes)
  713. if err != nil {
  714. return err
  715. }
  716. if len(cpuCosts) == 0 {
  717. log.Infof("Kubecost prometheus metrics not currently available. Ingest this server's /metrics endpoint to get that data.")
  718. }
  719. for node, costv := range cpuCosts {
  720. if _, ok := missingNodes[node]; ok {
  721. missingNodes[node].VCPUCost = fmt.Sprintf("%f", costv[0].Value)
  722. } else {
  723. log.DedupedWarningf(5, "Node `%s` in prometheus but not k8s api", node)
  724. }
  725. }
  726. for node, costv := range ramCosts {
  727. if _, ok := missingNodes[node]; ok {
  728. missingNodes[node].RAMCost = fmt.Sprintf("%f", costv[0].Value)
  729. }
  730. }
  731. for node, costv := range gpuCosts {
  732. if _, ok := missingNodes[node]; ok {
  733. missingNodes[node].GPUCost = fmt.Sprintf("%f", costv[0].Value)
  734. }
  735. }
  736. }
  737. return nil
  738. }
  739. // getContainerAllocation takes the max between request and usage. This function
  740. // returns a slice containing a single element describing the container's
  741. // allocation.
  742. //
  743. // Additionally, the timestamp of the allocation will be the highest value
  744. // timestamp between the two vectors. This mitigates situations where
  745. // Timestamp=0. This should have no effect on the metrics emitted by the
  746. // CostModelMetricsEmitter
  747. func getContainerAllocation(req *util.Vector, used *util.Vector, allocationType string) []*util.Vector {
  748. var result []*util.Vector
  749. if req != nil && used != nil {
  750. x1 := req.Value
  751. if math.IsNaN(x1) {
  752. log.Debugf("NaN value found during %s allocation calculation for requests.", allocationType)
  753. x1 = 0.0
  754. }
  755. y1 := used.Value
  756. if math.IsNaN(y1) {
  757. log.Debugf("NaN value found during %s allocation calculation for used.", allocationType)
  758. y1 = 0.0
  759. }
  760. result = []*util.Vector{
  761. {
  762. Value: math.Max(x1, y1),
  763. Timestamp: math.Max(req.Timestamp, used.Timestamp),
  764. },
  765. }
  766. if result[0].Value == 0 && result[0].Timestamp == 0 {
  767. log.Debugf("No request or usage data found during %s allocation calculation. Setting allocation to 0.", allocationType)
  768. }
  769. } else if req != nil {
  770. result = []*util.Vector{
  771. {
  772. Value: req.Value,
  773. Timestamp: req.Timestamp,
  774. },
  775. }
  776. } else if used != nil {
  777. result = []*util.Vector{
  778. {
  779. Value: used.Value,
  780. Timestamp: used.Timestamp,
  781. },
  782. }
  783. } else {
  784. log.Debugf("No request or usage data found during %s allocation calculation. Setting allocation to 0.", allocationType)
  785. result = []*util.Vector{
  786. {
  787. Value: 0,
  788. Timestamp: float64(time.Now().UTC().Unix()),
  789. },
  790. }
  791. }
  792. return result
  793. }
  794. func addPVData(cache clustercache.ClusterCache, pvClaimMapping map[string]*PersistentVolumeClaimData, cloud costAnalyzerCloud.Provider) error {
  795. cfg, err := cloud.GetConfig()
  796. if err != nil {
  797. return err
  798. }
  799. // Pull a region from the first node
  800. var defaultRegion string
  801. nodeList := cache.GetAllNodes()
  802. if len(nodeList) > 0 {
  803. defaultRegion, _ = util.GetRegion(nodeList[0].Labels)
  804. }
  805. storageClasses := cache.GetAllStorageClasses()
  806. storageClassMap := make(map[string]map[string]string)
  807. for _, storageClass := range storageClasses {
  808. params := storageClass.Parameters
  809. storageClassMap[storageClass.ObjectMeta.Name] = params
  810. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  811. storageClassMap["default"] = params
  812. storageClassMap[""] = params
  813. }
  814. }
  815. pvs := cache.GetAllPersistentVolumes()
  816. pvMap := make(map[string]*costAnalyzerCloud.PV)
  817. for _, pv := range pvs {
  818. parameters, ok := storageClassMap[pv.Spec.StorageClassName]
  819. if !ok {
  820. log.Debugf("Unable to find parameters for storage class \"%s\". Does pv \"%s\" have a storageClassName?", pv.Spec.StorageClassName, pv.Name)
  821. }
  822. var region string
  823. if r, ok := util.GetRegion(pv.Labels); ok {
  824. region = r
  825. } else {
  826. region = defaultRegion
  827. }
  828. cacPv := &costAnalyzerCloud.PV{
  829. Class: pv.Spec.StorageClassName,
  830. Region: region,
  831. Parameters: parameters,
  832. }
  833. err := GetPVCost(cacPv, pv, cloud, region)
  834. if err != nil {
  835. return err
  836. }
  837. pvMap[pv.Name] = cacPv
  838. }
  839. for _, pvc := range pvClaimMapping {
  840. if vol, ok := pvMap[pvc.VolumeName]; ok {
  841. pvc.Volume = vol
  842. } else {
  843. log.Debugf("PV not found, using default")
  844. pvc.Volume = &costAnalyzerCloud.PV{
  845. Cost: cfg.Storage,
  846. }
  847. }
  848. }
  849. return nil
  850. }
  851. func GetPVCost(pv *costAnalyzerCloud.PV, kpv *v1.PersistentVolume, cp costAnalyzerCloud.Provider, defaultRegion string) error {
  852. cfg, err := cp.GetConfig()
  853. if err != nil {
  854. return err
  855. }
  856. key := cp.GetPVKey(kpv, pv.Parameters, defaultRegion)
  857. pv.ProviderID = key.ID()
  858. pvWithCost, err := cp.PVPricing(key)
  859. if err != nil {
  860. pv.Cost = cfg.Storage
  861. return err
  862. }
  863. if pvWithCost == nil || pvWithCost.Cost == "" {
  864. pv.Cost = cfg.Storage
  865. return nil // set default cost
  866. }
  867. pv.Cost = pvWithCost.Cost
  868. return nil
  869. }
  870. func (cm *CostModel) GetPricingSourceCounts() (*costAnalyzerCloud.PricingMatchMetadata, error) {
  871. if cm.pricingMetadata != nil {
  872. return cm.pricingMetadata, nil
  873. } else {
  874. return nil, fmt.Errorf("Node costs not yet calculated")
  875. }
  876. }
  877. func (cm *CostModel) GetNodeCost(cp costAnalyzerCloud.Provider) (map[string]*costAnalyzerCloud.Node, error) {
  878. cfg, err := cp.GetConfig()
  879. if err != nil {
  880. return nil, err
  881. }
  882. nodeList := cm.Cache.GetAllNodes()
  883. nodes := make(map[string]*costAnalyzerCloud.Node)
  884. vgpuCount, err := getAllocatableVGPUs(cm.Cache)
  885. if err != nil {
  886. return nil, err
  887. }
  888. vgpuCoeff := 10.0
  889. if vgpuCount > 0.0 {
  890. vgpuCoeff = vgpuCount
  891. }
  892. pmd := &costAnalyzerCloud.PricingMatchMetadata{
  893. TotalNodes: 0,
  894. PricingTypeCounts: make(map[costAnalyzerCloud.PricingType]int),
  895. }
  896. for _, n := range nodeList {
  897. name := n.GetObjectMeta().GetName()
  898. nodeLabels := n.GetObjectMeta().GetLabels()
  899. nodeLabels["providerID"] = n.Spec.ProviderID
  900. pmd.TotalNodes++
  901. cnode, _, err := cp.NodePricing(cp.GetKey(nodeLabels, n))
  902. if err != nil {
  903. log.Infof("Error getting node pricing. Error: %s", err.Error())
  904. if cnode != nil {
  905. nodes[name] = cnode
  906. continue
  907. } else {
  908. cnode = &costAnalyzerCloud.Node{
  909. VCPUCost: cfg.CPU,
  910. RAMCost: cfg.RAM,
  911. }
  912. }
  913. }
  914. if _, ok := pmd.PricingTypeCounts[cnode.PricingType]; ok {
  915. pmd.PricingTypeCounts[cnode.PricingType]++
  916. } else {
  917. pmd.PricingTypeCounts[cnode.PricingType] = 1
  918. }
  919. newCnode := *cnode
  920. if newCnode.InstanceType == "" {
  921. it, _ := util.GetInstanceType(n.Labels)
  922. newCnode.InstanceType = it
  923. }
  924. if newCnode.Region == "" {
  925. region, _ := util.GetRegion(n.Labels)
  926. newCnode.Region = region
  927. }
  928. if newCnode.ArchType == "" {
  929. arch, _ := util.GetArchType(n.Labels)
  930. newCnode.ArchType = arch
  931. }
  932. newCnode.ProviderID = n.Spec.ProviderID
  933. var cpu float64
  934. if newCnode.VCPU == "" {
  935. cpu = float64(n.Status.Capacity.Cpu().Value())
  936. newCnode.VCPU = n.Status.Capacity.Cpu().String()
  937. } else {
  938. cpu, err = strconv.ParseFloat(newCnode.VCPU, 64)
  939. if err != nil {
  940. log.Warnf("parsing VCPU value: \"%s\" as float64", newCnode.VCPU)
  941. }
  942. }
  943. if math.IsNaN(cpu) {
  944. log.Warnf("cpu parsed as NaN. Setting to 0.")
  945. cpu = 0
  946. }
  947. var ram float64
  948. if newCnode.RAM == "" {
  949. newCnode.RAM = n.Status.Capacity.Memory().String()
  950. }
  951. ram = float64(n.Status.Capacity.Memory().Value())
  952. if math.IsNaN(ram) {
  953. log.Warnf("ram parsed as NaN. Setting to 0.")
  954. ram = 0
  955. }
  956. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  957. // Azure does not seem to provide a GPU count in its pricing API. GKE supports attaching multiple GPUs
  958. // So the k8s api will often report more accurate results for GPU count under status > capacity > nvidia.com/gpu than the cloud providers billing data
  959. // not all providers are guaranteed to use this, so don't overwrite a Provider assignment if we can't find something under that capacity exists
  960. gpuc := 0.0
  961. q, ok := n.Status.Capacity["nvidia.com/gpu"]
  962. _, hasReplicas := n.Labels["nvidia.com/gpu.replicas"]
  963. if ok && !hasReplicas {
  964. gpuCount := q.Value()
  965. if gpuCount != 0 {
  966. newCnode.GPU = fmt.Sprintf("%d", gpuCount)
  967. newCnode.VGPU = newCnode.GPU
  968. gpuc = float64(gpuCount)
  969. }
  970. } else if hasReplicas { // See https://docs.nvidia.com/datacenter/cloud-native/gpu-operator/latest/gpu-sharing.html
  971. if q.Value() == 0 {
  972. q = n.Status.Capacity["nvidia.com/gpu.shared"]
  973. }
  974. g, ok := n.Labels["nvidia.com/gpu.count"]
  975. if ok {
  976. newCnode.GPU = g
  977. } else {
  978. newCnode.GPU = fmt.Sprintf("%d", 0)
  979. }
  980. newCnode.VGPU = fmt.Sprintf("%d", q.Value())
  981. } else if g, ok := n.Status.Capacity["k8s.amazonaws.com/vgpu"]; ok {
  982. gpuCount := g.Value()
  983. if gpuCount != 0 {
  984. newCnode.GPU = fmt.Sprintf("%d", int(float64(gpuCount)/vgpuCoeff))
  985. newCnode.VGPU = fmt.Sprintf("%d", gpuCount)
  986. gpuc = float64(gpuCount) / vgpuCoeff
  987. }
  988. } else {
  989. gpuc, err = strconv.ParseFloat(newCnode.GPU, 64)
  990. if err != nil {
  991. gpuc = 0.0
  992. }
  993. }
  994. if math.IsNaN(gpuc) {
  995. log.Warnf("gpu count parsed as NaN. Setting to 0.")
  996. gpuc = 0.0
  997. }
  998. // Special case for SUSE rancher, since it won't behave with normal
  999. // calculations, courtesy of the instance type not being "real" (a
  1000. // recognizable AWS instance type.)
  1001. if newCnode.InstanceType == "rke2" {
  1002. log.Infof(
  1003. "Found a SUSE Rancher node %s, defaulting and skipping math",
  1004. cp.GetKey(nodeLabels, n).Features(),
  1005. )
  1006. defaultCPUCorePrice, err := strconv.ParseFloat(cfg.CPU, 64)
  1007. if err != nil {
  1008. log.Errorf("Could not parse default cpu price")
  1009. defaultCPUCorePrice = 0
  1010. }
  1011. if math.IsNaN(defaultCPUCorePrice) {
  1012. log.Warnf("defaultCPU parsed as NaN. Setting to 0.")
  1013. defaultCPUCorePrice = 0
  1014. }
  1015. defaultRAMPrice, err := strconv.ParseFloat(cfg.RAM, 64)
  1016. if err != nil {
  1017. log.Errorf("Could not parse default ram price")
  1018. defaultRAMPrice = 0
  1019. }
  1020. if math.IsNaN(defaultRAMPrice) {
  1021. log.Warnf("defaultRAM parsed as NaN. Setting to 0.")
  1022. defaultRAMPrice = 0
  1023. }
  1024. defaultGPUPrice, err := strconv.ParseFloat(cfg.GPU, 64)
  1025. if err != nil {
  1026. log.Errorf("Could not parse default gpu price")
  1027. defaultGPUPrice = 0
  1028. }
  1029. if math.IsNaN(defaultGPUPrice) {
  1030. log.Warnf("defaultGPU parsed as NaN. Setting to 0.")
  1031. defaultGPUPrice = 0
  1032. }
  1033. // Just say no to doing the ratios!
  1034. cpuCost := defaultCPUCorePrice * cpu
  1035. gpuCost := defaultGPUPrice * gpuc
  1036. ramCost := defaultRAMPrice * ram
  1037. nodeCost := cpuCost + gpuCost + ramCost
  1038. newCnode.Cost = fmt.Sprintf("%f", nodeCost)
  1039. newCnode.VCPUCost = fmt.Sprintf("%f", defaultCPUCorePrice)
  1040. newCnode.GPUCost = fmt.Sprintf("%f", defaultGPUPrice)
  1041. newCnode.RAMCost = fmt.Sprintf("%f", defaultRAMPrice)
  1042. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  1043. } else if newCnode.GPU != "" && newCnode.GPUCost == "" {
  1044. // was the big thing to investigate. All the funky ratio math
  1045. // we were doing was messing with their default pricing. for SUSE Rancher.
  1046. // We reach this when a GPU is detected on a node, but no cost for
  1047. // the GPU is defined in the OnDemand pricing. Calculate ratios of
  1048. // CPU to RAM and GPU to RAM costs, then distribute the total node
  1049. // cost among the CPU, RAM, and GPU.
  1050. log.Tracef("GPU without cost found for %s, calculating...", cp.GetKey(nodeLabels, n).Features())
  1051. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  1052. if err != nil {
  1053. log.Errorf("Could not parse default cpu price")
  1054. defaultCPU = 0
  1055. }
  1056. if math.IsNaN(defaultCPU) {
  1057. log.Warnf("defaultCPU parsed as NaN. Setting to 0.")
  1058. defaultCPU = 0
  1059. }
  1060. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  1061. if err != nil {
  1062. log.Errorf("Could not parse default ram price")
  1063. defaultRAM = 0
  1064. }
  1065. if math.IsNaN(defaultRAM) {
  1066. log.Warnf("defaultRAM parsed as NaN. Setting to 0.")
  1067. defaultRAM = 0
  1068. }
  1069. defaultGPU, err := strconv.ParseFloat(cfg.GPU, 64)
  1070. if err != nil {
  1071. log.Errorf("Could not parse default gpu price")
  1072. defaultGPU = 0
  1073. }
  1074. if math.IsNaN(defaultGPU) {
  1075. log.Warnf("defaultGPU parsed as NaN. Setting to 0.")
  1076. defaultGPU = 0
  1077. }
  1078. cpuToRAMRatio := defaultCPU / defaultRAM
  1079. if math.IsNaN(cpuToRAMRatio) {
  1080. log.Warnf("cpuToRAMRatio[defaultCPU: %f / defaultRAM: %f] is NaN. Setting to 10.", defaultCPU, defaultRAM)
  1081. cpuToRAMRatio = 10
  1082. }
  1083. gpuToRAMRatio := defaultGPU / defaultRAM
  1084. if math.IsNaN(gpuToRAMRatio) {
  1085. log.Warnf("gpuToRAMRatio is NaN. Setting to 100.")
  1086. gpuToRAMRatio = 100
  1087. }
  1088. ramGB := ram / 1024 / 1024 / 1024
  1089. if math.IsNaN(ramGB) {
  1090. log.Warnf("ramGB is NaN. Setting to 0.")
  1091. ramGB = 0
  1092. }
  1093. ramMultiple := gpuc*gpuToRAMRatio + cpu*cpuToRAMRatio + ramGB
  1094. if math.IsNaN(ramMultiple) {
  1095. log.Warnf("ramMultiple is NaN. Setting to 0.")
  1096. ramMultiple = 0
  1097. }
  1098. var nodePrice float64
  1099. if newCnode.Cost != "" {
  1100. nodePrice, err = strconv.ParseFloat(newCnode.Cost, 64)
  1101. if err != nil {
  1102. log.Errorf("Could not parse total node price")
  1103. return nil, err
  1104. }
  1105. } else if newCnode.VCPUCost != "" {
  1106. nodePrice, err = strconv.ParseFloat(newCnode.VCPUCost, 64) // all the price was allocated to the CPU
  1107. if err != nil {
  1108. log.Errorf("Could not parse node vcpu price")
  1109. return nil, err
  1110. }
  1111. } else { // add case to use default pricing model when API data fails.
  1112. log.Debugf("No node price or CPUprice found, falling back to default")
  1113. nodePrice = defaultCPU*cpu + defaultRAM*ram + gpuc*defaultGPU
  1114. }
  1115. if math.IsNaN(nodePrice) {
  1116. log.Warnf("nodePrice parsed as NaN. Setting to 0.")
  1117. nodePrice = 0
  1118. }
  1119. ramPrice := (nodePrice / ramMultiple)
  1120. if math.IsNaN(ramPrice) {
  1121. log.Warnf("ramPrice[nodePrice: %f / ramMultiple: %f] parsed as NaN. Setting to 0.", nodePrice, ramMultiple)
  1122. ramPrice = 0
  1123. }
  1124. cpuPrice := ramPrice * cpuToRAMRatio
  1125. gpuPrice := ramPrice * gpuToRAMRatio
  1126. newCnode.VCPUCost = fmt.Sprintf("%f", cpuPrice)
  1127. newCnode.RAMCost = fmt.Sprintf("%f", ramPrice)
  1128. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  1129. newCnode.GPUCost = fmt.Sprintf("%f", gpuPrice)
  1130. } else if newCnode.RAMCost == "" {
  1131. // We reach this when no RAM cost is defined in the OnDemand
  1132. // pricing. It calculates a cpuToRAMRatio and ramMultiple to
  1133. // distrubte the total node cost among CPU and RAM costs.
  1134. log.Tracef("No RAM cost found for %s, calculating...", cp.GetKey(nodeLabels, n).Features())
  1135. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  1136. if err != nil {
  1137. log.Warnf("Could not parse default cpu price")
  1138. defaultCPU = 0
  1139. }
  1140. if math.IsNaN(defaultCPU) {
  1141. log.Warnf("defaultCPU parsed as NaN. Setting to 0.")
  1142. defaultCPU = 0
  1143. }
  1144. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  1145. if err != nil {
  1146. log.Warnf("Could not parse default ram price")
  1147. defaultRAM = 0
  1148. }
  1149. if math.IsNaN(defaultRAM) {
  1150. log.Warnf("defaultRAM parsed as NaN. Setting to 0.")
  1151. defaultRAM = 0
  1152. }
  1153. cpuToRAMRatio := defaultCPU / defaultRAM
  1154. if math.IsNaN(cpuToRAMRatio) {
  1155. log.Warnf("cpuToRAMRatio[defaultCPU: %f / defaultRAM: %f] is NaN. Setting to 10.", defaultCPU, defaultRAM)
  1156. cpuToRAMRatio = 10
  1157. }
  1158. ramGB := ram / 1024 / 1024 / 1024
  1159. if math.IsNaN(ramGB) {
  1160. log.Warnf("ramGB is NaN. Setting to 0.")
  1161. ramGB = 0
  1162. }
  1163. ramMultiple := cpu*cpuToRAMRatio + ramGB
  1164. if math.IsNaN(ramMultiple) {
  1165. log.Warnf("ramMultiple is NaN. Setting to 0.")
  1166. ramMultiple = 0
  1167. }
  1168. var nodePrice float64
  1169. if newCnode.Cost != "" {
  1170. nodePrice, err = strconv.ParseFloat(newCnode.Cost, 64)
  1171. if err != nil {
  1172. log.Warnf("Could not parse total node price")
  1173. return nil, err
  1174. }
  1175. if newCnode.GPUCost != "" {
  1176. gpuPrice, err := strconv.ParseFloat(newCnode.GPUCost, 64)
  1177. if err != nil {
  1178. log.Warnf("Could not parse node gpu price")
  1179. return nil, err
  1180. }
  1181. nodePrice = nodePrice - gpuPrice // remove the gpuPrice from the total, we're just costing out RAM and CPU.
  1182. }
  1183. } else if newCnode.VCPUCost != "" {
  1184. nodePrice, err = strconv.ParseFloat(newCnode.VCPUCost, 64) // all the price was allocated to the CPU
  1185. if err != nil {
  1186. log.Warnf("Could not parse node vcpu price")
  1187. return nil, err
  1188. }
  1189. } else { // add case to use default pricing model when API data fails.
  1190. log.Debugf("No node price or CPUprice found, falling back to default")
  1191. nodePrice = defaultCPU*cpu + defaultRAM*ramGB
  1192. }
  1193. if math.IsNaN(nodePrice) {
  1194. log.Warnf("nodePrice parsed as NaN. Setting to 0.")
  1195. nodePrice = 0
  1196. }
  1197. ramPrice := (nodePrice / ramMultiple)
  1198. if math.IsNaN(ramPrice) {
  1199. log.Warnf("ramPrice[nodePrice: %f / ramMultiple: %f] parsed as NaN. Setting to 0.", nodePrice, ramMultiple)
  1200. ramPrice = 0
  1201. }
  1202. cpuPrice := ramPrice * cpuToRAMRatio
  1203. if defaultRAM != 0 {
  1204. newCnode.VCPUCost = fmt.Sprintf("%f", cpuPrice)
  1205. newCnode.RAMCost = fmt.Sprintf("%f", ramPrice)
  1206. } else { // just assign the full price to CPU
  1207. if cpu != 0 {
  1208. newCnode.VCPUCost = fmt.Sprintf("%f", nodePrice/cpu)
  1209. } else {
  1210. newCnode.VCPUCost = fmt.Sprintf("%f", nodePrice)
  1211. }
  1212. }
  1213. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  1214. log.Tracef("Computed \"%s\" RAM Cost := %v", name, newCnode.RAMCost)
  1215. }
  1216. nodes[name] = &newCnode
  1217. }
  1218. cm.pricingMetadata = pmd
  1219. cp.ApplyReservedInstancePricing(nodes)
  1220. return nodes, nil
  1221. }
  1222. // TODO: drop some logs
  1223. func (cm *CostModel) GetLBCost(cp costAnalyzerCloud.Provider) (map[serviceKey]*costAnalyzerCloud.LoadBalancer, error) {
  1224. // for fetching prices from cloud provider
  1225. // cfg, err := cp.GetConfig()
  1226. // if err != nil {
  1227. // return nil, err
  1228. // }
  1229. servicesList := cm.Cache.GetAllServices()
  1230. loadBalancerMap := make(map[serviceKey]*costAnalyzerCloud.LoadBalancer)
  1231. for _, service := range servicesList {
  1232. namespace := service.GetObjectMeta().GetNamespace()
  1233. name := service.GetObjectMeta().GetName()
  1234. key := serviceKey{
  1235. Cluster: env.GetClusterID(),
  1236. Namespace: namespace,
  1237. Service: name,
  1238. }
  1239. if service.Spec.Type == "LoadBalancer" {
  1240. loadBalancer, err := cp.LoadBalancerPricing()
  1241. if err != nil {
  1242. return nil, err
  1243. }
  1244. newLoadBalancer := *loadBalancer
  1245. for _, loadBalancerIngress := range service.Status.LoadBalancer.Ingress {
  1246. address := loadBalancerIngress.IP
  1247. // Some cloud providers use hostname rather than IP
  1248. if address == "" {
  1249. address = loadBalancerIngress.Hostname
  1250. }
  1251. newLoadBalancer.IngressIPAddresses = append(newLoadBalancer.IngressIPAddresses, address)
  1252. }
  1253. loadBalancerMap[key] = &newLoadBalancer
  1254. }
  1255. }
  1256. return loadBalancerMap, nil
  1257. }
  1258. func getPodServices(cache clustercache.ClusterCache, podList []*v1.Pod, clusterID string) (map[string]map[string][]string, error) {
  1259. servicesList := cache.GetAllServices()
  1260. podServicesMapping := make(map[string]map[string][]string)
  1261. for _, service := range servicesList {
  1262. namespace := service.GetObjectMeta().GetNamespace()
  1263. name := service.GetObjectMeta().GetName()
  1264. key := namespace + "," + clusterID
  1265. if _, ok := podServicesMapping[key]; !ok {
  1266. podServicesMapping[key] = make(map[string][]string)
  1267. }
  1268. s := labels.Nothing()
  1269. if service.Spec.Selector != nil && len(service.Spec.Selector) > 0 {
  1270. s = labels.Set(service.Spec.Selector).AsSelectorPreValidated()
  1271. }
  1272. for _, pod := range podList {
  1273. labelSet := labels.Set(pod.GetObjectMeta().GetLabels())
  1274. if s.Matches(labelSet) && pod.GetObjectMeta().GetNamespace() == namespace {
  1275. services, ok := podServicesMapping[key][pod.GetObjectMeta().GetName()]
  1276. if ok {
  1277. podServicesMapping[key][pod.GetObjectMeta().GetName()] = append(services, name)
  1278. } else {
  1279. podServicesMapping[key][pod.GetObjectMeta().GetName()] = []string{name}
  1280. }
  1281. }
  1282. }
  1283. }
  1284. return podServicesMapping, nil
  1285. }
  1286. func getPodStatefulsets(cache clustercache.ClusterCache, podList []*v1.Pod, clusterID string) (map[string]map[string][]string, error) {
  1287. ssList := cache.GetAllStatefulSets()
  1288. podSSMapping := make(map[string]map[string][]string) // namespace: podName: [deploymentNames]
  1289. for _, ss := range ssList {
  1290. namespace := ss.GetObjectMeta().GetNamespace()
  1291. name := ss.GetObjectMeta().GetName()
  1292. key := namespace + "," + clusterID
  1293. if _, ok := podSSMapping[key]; !ok {
  1294. podSSMapping[key] = make(map[string][]string)
  1295. }
  1296. s, err := metav1.LabelSelectorAsSelector(ss.Spec.Selector)
  1297. if err != nil {
  1298. log.Errorf("Error doing deployment label conversion: " + err.Error())
  1299. }
  1300. for _, pod := range podList {
  1301. labelSet := labels.Set(pod.GetObjectMeta().GetLabels())
  1302. if s.Matches(labelSet) && pod.GetObjectMeta().GetNamespace() == namespace {
  1303. sss, ok := podSSMapping[key][pod.GetObjectMeta().GetName()]
  1304. if ok {
  1305. podSSMapping[key][pod.GetObjectMeta().GetName()] = append(sss, name)
  1306. } else {
  1307. podSSMapping[key][pod.GetObjectMeta().GetName()] = []string{name}
  1308. }
  1309. }
  1310. }
  1311. }
  1312. return podSSMapping, nil
  1313. }
  1314. func getPodDeployments(cache clustercache.ClusterCache, podList []*v1.Pod, clusterID string) (map[string]map[string][]string, error) {
  1315. deploymentsList := cache.GetAllDeployments()
  1316. podDeploymentsMapping := make(map[string]map[string][]string) // namespace: podName: [deploymentNames]
  1317. for _, deployment := range deploymentsList {
  1318. namespace := deployment.GetObjectMeta().GetNamespace()
  1319. name := deployment.GetObjectMeta().GetName()
  1320. key := namespace + "," + clusterID
  1321. if _, ok := podDeploymentsMapping[key]; !ok {
  1322. podDeploymentsMapping[key] = make(map[string][]string)
  1323. }
  1324. s, err := metav1.LabelSelectorAsSelector(deployment.Spec.Selector)
  1325. if err != nil {
  1326. log.Errorf("Error doing deployment label conversion: " + err.Error())
  1327. }
  1328. for _, pod := range podList {
  1329. labelSet := labels.Set(pod.GetObjectMeta().GetLabels())
  1330. if s.Matches(labelSet) && pod.GetObjectMeta().GetNamespace() == namespace {
  1331. deployments, ok := podDeploymentsMapping[key][pod.GetObjectMeta().GetName()]
  1332. if ok {
  1333. podDeploymentsMapping[key][pod.GetObjectMeta().GetName()] = append(deployments, name)
  1334. } else {
  1335. podDeploymentsMapping[key][pod.GetObjectMeta().GetName()] = []string{name}
  1336. }
  1337. }
  1338. }
  1339. }
  1340. return podDeploymentsMapping, nil
  1341. }
  1342. func getPodDeploymentsWithMetrics(deploymentLabels map[string]map[string]string, podLabels map[string]map[string]string) (map[string]map[string][]string, error) {
  1343. podDeploymentsMapping := make(map[string]map[string][]string)
  1344. for depKey, depLabels := range deploymentLabels {
  1345. kt, err := NewKeyTuple(depKey)
  1346. if err != nil {
  1347. continue
  1348. }
  1349. namespace := kt.Namespace()
  1350. name := kt.Key()
  1351. clusterID := kt.ClusterID()
  1352. key := namespace + "," + clusterID
  1353. if _, ok := podDeploymentsMapping[key]; !ok {
  1354. podDeploymentsMapping[key] = make(map[string][]string)
  1355. }
  1356. s := labels.Set(depLabels).AsSelectorPreValidated()
  1357. for podKey, pLabels := range podLabels {
  1358. pkey, err := NewKeyTuple(podKey)
  1359. if err != nil {
  1360. continue
  1361. }
  1362. podNamespace := pkey.Namespace()
  1363. podName := pkey.Key()
  1364. podClusterID := pkey.ClusterID()
  1365. labelSet := labels.Set(pLabels)
  1366. if s.Matches(labelSet) && podNamespace == namespace && podClusterID == clusterID {
  1367. deployments, ok := podDeploymentsMapping[key][podName]
  1368. if ok {
  1369. podDeploymentsMapping[key][podName] = append(deployments, name)
  1370. } else {
  1371. podDeploymentsMapping[key][podName] = []string{name}
  1372. }
  1373. }
  1374. }
  1375. }
  1376. // Remove any duplicate data created by metric names
  1377. pruneDuplicateData(podDeploymentsMapping)
  1378. return podDeploymentsMapping, nil
  1379. }
  1380. func getPodServicesWithMetrics(serviceLabels map[string]map[string]string, podLabels map[string]map[string]string) (map[string]map[string][]string, error) {
  1381. podServicesMapping := make(map[string]map[string][]string)
  1382. for servKey, servLabels := range serviceLabels {
  1383. kt, err := NewKeyTuple(servKey)
  1384. if err != nil {
  1385. continue
  1386. }
  1387. namespace := kt.Namespace()
  1388. name := kt.Key()
  1389. clusterID := kt.ClusterID()
  1390. key := namespace + "," + clusterID
  1391. if _, ok := podServicesMapping[key]; !ok {
  1392. podServicesMapping[key] = make(map[string][]string)
  1393. }
  1394. s := labels.Nothing()
  1395. if servLabels != nil && len(servLabels) > 0 {
  1396. s = labels.Set(servLabels).AsSelectorPreValidated()
  1397. }
  1398. for podKey, pLabels := range podLabels {
  1399. pkey, err := NewKeyTuple(podKey)
  1400. if err != nil {
  1401. continue
  1402. }
  1403. podNamespace := pkey.Namespace()
  1404. podName := pkey.Key()
  1405. podClusterID := pkey.ClusterID()
  1406. labelSet := labels.Set(pLabels)
  1407. if s.Matches(labelSet) && podNamespace == namespace && podClusterID == clusterID {
  1408. services, ok := podServicesMapping[key][podName]
  1409. if ok {
  1410. podServicesMapping[key][podName] = append(services, name)
  1411. } else {
  1412. podServicesMapping[key][podName] = []string{name}
  1413. }
  1414. }
  1415. }
  1416. }
  1417. // Remove any duplicate data created by metric names
  1418. pruneDuplicateData(podServicesMapping)
  1419. return podServicesMapping, nil
  1420. }
  1421. // This method alleviates an issue with metrics that used a '_' to replace '-' in deployment
  1422. // and service names. To avoid counting these as multiple deployments/services, we'll remove
  1423. // the '_' version. Not optimal, but takes care of the issue
  1424. func pruneDuplicateData(data map[string]map[string][]string) {
  1425. for _, podMap := range data {
  1426. for podName, values := range podMap {
  1427. podMap[podName] = pruneDuplicates(values)
  1428. }
  1429. }
  1430. }
  1431. // Determine if there is an underscore in the value of a slice. If so, replace _ with -, and then
  1432. // check to see if the result exists in the slice. If both are true, then we DO NOT include that
  1433. // original value in the new slice.
  1434. func pruneDuplicates(s []string) []string {
  1435. m := sliceToSet(s)
  1436. for _, v := range s {
  1437. if strings.Contains(v, "_") {
  1438. name := strings.Replace(v, "_", "-", -1)
  1439. if !m[name] {
  1440. m[name] = true
  1441. }
  1442. delete(m, v)
  1443. }
  1444. }
  1445. return setToSlice(m)
  1446. }
  1447. // Creates a map[string]bool containing the slice values as keys
  1448. func sliceToSet(s []string) map[string]bool {
  1449. m := make(map[string]bool)
  1450. for _, v := range s {
  1451. m[v] = true
  1452. }
  1453. return m
  1454. }
  1455. func setToSlice(m map[string]bool) []string {
  1456. var result []string
  1457. for k := range m {
  1458. result = append(result, k)
  1459. }
  1460. return result
  1461. }
  1462. func costDataPassesFilters(cm clusters.ClusterMap, costs *CostData, namespace string, cluster string) bool {
  1463. passesNamespace := namespace == "" || costs.Namespace == namespace
  1464. passesCluster := cluster == "" || costs.ClusterID == cluster || costs.ClusterName == cluster
  1465. return passesNamespace && passesCluster
  1466. }
  1467. // Finds the a closest multiple less than value
  1468. func floorMultiple(value int64, multiple int64) int64 {
  1469. return (value / multiple) * multiple
  1470. }
  1471. // Attempt to create a key for the request. Reduce the times to minutes in order to more easily group requests based on
  1472. // real time ranges. If for any reason, the key generation fails, return a uuid to ensure uniqueness.
  1473. func requestKeyFor(window opencost.Window, resolution time.Duration, filterNamespace string, filterCluster string, remoteEnabled bool) string {
  1474. keyLayout := "2006-01-02T15:04Z"
  1475. // We "snap" start time and duration to their closest 5 min multiple less than itself, by
  1476. // applying a snapped duration to a snapped start time.
  1477. durMins := int64(window.Minutes())
  1478. durMins = floorMultiple(durMins, 5)
  1479. sMins := int64(window.Start().Minute())
  1480. sOffset := sMins - floorMultiple(sMins, 5)
  1481. sTime := window.Start().Add(-time.Duration(sOffset) * time.Minute)
  1482. eTime := window.Start().Add(time.Duration(durMins) * time.Minute)
  1483. startKey := sTime.Format(keyLayout)
  1484. endKey := eTime.Format(keyLayout)
  1485. return fmt.Sprintf("%s,%s,%s,%s,%s,%t", startKey, endKey, resolution.String(), filterNamespace, filterCluster, remoteEnabled)
  1486. }
  1487. // ComputeCostDataRange executes a range query for cost data.
  1488. // Note that "offset" represents the time between the function call and "endString", and is also passed for convenience
  1489. func (cm *CostModel) ComputeCostDataRange(cli prometheusClient.Client, cp costAnalyzerCloud.Provider, window opencost.Window, resolution time.Duration, filterNamespace string, filterCluster string, remoteEnabled bool) (map[string]*CostData, error) {
  1490. // Create a request key for request grouping. This key will be used to represent the cost-model result
  1491. // for the specific inputs to prevent multiple queries for identical data.
  1492. key := requestKeyFor(window, resolution, filterNamespace, filterCluster, remoteEnabled)
  1493. log.Debugf("ComputeCostDataRange with Key: %s", key)
  1494. // If there is already a request out that uses the same data, wait for it to return to share the results.
  1495. // Otherwise, start executing.
  1496. result, err, _ := cm.RequestGroup.Do(key, func() (interface{}, error) {
  1497. return cm.costDataRange(cli, cp, window, resolution, filterNamespace, filterCluster, remoteEnabled)
  1498. })
  1499. data, ok := result.(map[string]*CostData)
  1500. if !ok {
  1501. return nil, fmt.Errorf("Failed to cast result as map[string]*CostData")
  1502. }
  1503. return data, err
  1504. }
  1505. func (cm *CostModel) costDataRange(cli prometheusClient.Client, cp costAnalyzerCloud.Provider, window opencost.Window, resolution time.Duration, filterNamespace string, filterCluster string, remoteEnabled bool) (map[string]*CostData, error) {
  1506. clusterID := env.GetClusterID()
  1507. // durHrs := end.Sub(start).Hours() + 1
  1508. if window.IsOpen() {
  1509. return nil, fmt.Errorf("illegal window: %s", window)
  1510. }
  1511. start := *window.Start()
  1512. end := *window.End()
  1513. // Snap resolution to the nearest minute
  1514. resMins := int64(math.Trunc(resolution.Minutes()))
  1515. if resMins == 0 {
  1516. return nil, fmt.Errorf("resolution must be greater than 0.0")
  1517. }
  1518. resolution = time.Duration(resMins) * time.Minute
  1519. // Warn if resolution does not evenly divide window
  1520. if int64(window.Minutes())%int64(resolution.Minutes()) != 0 {
  1521. log.Warnf("CostDataRange: window should be divisible by resolution or else samples may be missed: %s %% %s = %dm", window, resolution, int64(window.Minutes())%int64(resolution.Minutes()))
  1522. }
  1523. // Convert to Prometheus-style duration string in terms of m or h
  1524. resStr := fmt.Sprintf("%dm", resMins)
  1525. if resMins%60 == 0 {
  1526. resStr = fmt.Sprintf("%dh", resMins/60)
  1527. }
  1528. if remoteEnabled {
  1529. remoteLayout := "2006-01-02T15:04:05Z"
  1530. remoteStartStr := window.Start().Format(remoteLayout)
  1531. remoteEndStr := window.End().Format(remoteLayout)
  1532. log.Infof("Using remote database for query from %s to %s with window %s", remoteStartStr, remoteEndStr, resolution)
  1533. return CostDataRangeFromSQL("", "", resolution.String(), remoteStartStr, remoteEndStr)
  1534. }
  1535. scrapeIntervalSeconds := cm.ScrapeInterval.Seconds()
  1536. ctx := prom.NewNamedContext(cli, prom.ComputeCostDataRangeContextName)
  1537. queryRAMAlloc := fmt.Sprintf(queryRAMAllocationByteHours, env.GetPromClusterFilter(), resStr, env.GetPromClusterLabel(), scrapeIntervalSeconds)
  1538. queryCPUAlloc := fmt.Sprintf(queryCPUAllocationVCPUHours, env.GetPromClusterFilter(), resStr, env.GetPromClusterLabel(), scrapeIntervalSeconds)
  1539. queryRAMRequests := fmt.Sprintf(queryRAMRequestsStr, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1540. queryRAMUsage := fmt.Sprintf(queryRAMUsageStr, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1541. queryCPURequests := fmt.Sprintf(queryCPURequestsStr, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1542. queryCPUUsage := fmt.Sprintf(queryCPUUsageStr, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1543. queryGPURequests := fmt.Sprintf(queryGPURequestsStr, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1544. queryPVRequests := fmt.Sprintf(queryPVRequestsStr, env.GetPromClusterFilter(), env.GetPromClusterLabel(), env.GetPromClusterLabel(), env.GetPromClusterFilter(), env.GetPromClusterLabel(), env.GetPromClusterLabel())
  1545. queryPVCAllocation := fmt.Sprintf(queryPVCAllocationFmt, env.GetPromClusterFilter(), resStr, env.GetPromClusterLabel(), scrapeIntervalSeconds)
  1546. queryPVHourlyCost := fmt.Sprintf(queryPVHourlyCostFmt, env.GetPromClusterFilter(), resStr)
  1547. queryNetZoneRequests := fmt.Sprintf(queryZoneNetworkUsage, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1548. queryNetRegionRequests := fmt.Sprintf(queryRegionNetworkUsage, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1549. queryNetInternetRequests := fmt.Sprintf(queryInternetNetworkUsage, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1550. queryNormalization := fmt.Sprintf(normalizationStr, env.GetPromClusterFilter(), resStr, "")
  1551. // Submit all queries for concurrent evaluation
  1552. resChRAMRequests := ctx.QueryRange(queryRAMRequests, start, end, resolution)
  1553. resChRAMUsage := ctx.QueryRange(queryRAMUsage, start, end, resolution)
  1554. resChRAMAlloc := ctx.QueryRange(queryRAMAlloc, start, end, resolution)
  1555. resChCPURequests := ctx.QueryRange(queryCPURequests, start, end, resolution)
  1556. resChCPUUsage := ctx.QueryRange(queryCPUUsage, start, end, resolution)
  1557. resChCPUAlloc := ctx.QueryRange(queryCPUAlloc, start, end, resolution)
  1558. resChGPURequests := ctx.QueryRange(queryGPURequests, start, end, resolution)
  1559. resChPVRequests := ctx.QueryRange(queryPVRequests, start, end, resolution)
  1560. resChPVCAlloc := ctx.QueryRange(queryPVCAllocation, start, end, resolution)
  1561. resChPVHourlyCost := ctx.QueryRange(queryPVHourlyCost, start, end, resolution)
  1562. resChNetZoneRequests := ctx.QueryRange(queryNetZoneRequests, start, end, resolution)
  1563. resChNetRegionRequests := ctx.QueryRange(queryNetRegionRequests, start, end, resolution)
  1564. resChNetInternetRequests := ctx.QueryRange(queryNetInternetRequests, start, end, resolution)
  1565. resChNSLabels := ctx.QueryRange(fmt.Sprintf(queryNSLabels, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1566. resChPodLabels := ctx.QueryRange(fmt.Sprintf(queryPodLabels, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1567. resChNSAnnotations := ctx.QueryRange(fmt.Sprintf(queryNSAnnotations, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1568. resChPodAnnotations := ctx.QueryRange(fmt.Sprintf(queryPodAnnotations, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1569. resChServiceLabels := ctx.QueryRange(fmt.Sprintf(queryServiceLabels, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1570. resChDeploymentLabels := ctx.QueryRange(fmt.Sprintf(queryDeploymentLabels, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1571. resChStatefulsetLabels := ctx.QueryRange(fmt.Sprintf(queryStatefulsetLabels, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1572. resChJobs := ctx.QueryRange(fmt.Sprintf(queryPodJobs, env.GetPromClusterFilter(), env.GetPromClusterLabel()), start, end, resolution)
  1573. resChDaemonsets := ctx.QueryRange(fmt.Sprintf(queryPodDaemonsets, env.GetPromClusterFilter(), env.GetPromClusterLabel()), start, end, resolution)
  1574. resChNormalization := ctx.QueryRange(queryNormalization, start, end, resolution)
  1575. // Pull k8s pod, controller, service, and namespace details
  1576. podlist := cm.Cache.GetAllPods()
  1577. podDeploymentsMapping, err := getPodDeployments(cm.Cache, podlist, clusterID)
  1578. if err != nil {
  1579. return nil, fmt.Errorf("error querying the kubernetes API: %s", err)
  1580. }
  1581. podStatefulsetsMapping, err := getPodStatefulsets(cm.Cache, podlist, clusterID)
  1582. if err != nil {
  1583. return nil, fmt.Errorf("error querying the kubernetes API: %s", err)
  1584. }
  1585. podServicesMapping, err := getPodServices(cm.Cache, podlist, clusterID)
  1586. if err != nil {
  1587. return nil, fmt.Errorf("error querying the kubernetes API: %s", err)
  1588. }
  1589. namespaceLabelsMapping, err := getNamespaceLabels(cm.Cache, clusterID)
  1590. if err != nil {
  1591. return nil, fmt.Errorf("error querying the kubernetes API: %s", err)
  1592. }
  1593. namespaceAnnotationsMapping, err := getNamespaceAnnotations(cm.Cache, clusterID)
  1594. if err != nil {
  1595. return nil, fmt.Errorf("error querying the kubernetes API: %s", err)
  1596. }
  1597. // Process query results. Handle errors afterwards using ctx.Errors.
  1598. resRAMRequests, _ := resChRAMRequests.Await()
  1599. resRAMUsage, _ := resChRAMUsage.Await()
  1600. resRAMAlloc, _ := resChRAMAlloc.Await()
  1601. resCPURequests, _ := resChCPURequests.Await()
  1602. resCPUUsage, _ := resChCPUUsage.Await()
  1603. resCPUAlloc, _ := resChCPUAlloc.Await()
  1604. resGPURequests, _ := resChGPURequests.Await()
  1605. resPVRequests, _ := resChPVRequests.Await()
  1606. resPVCAlloc, _ := resChPVCAlloc.Await()
  1607. resPVHourlyCost, _ := resChPVHourlyCost.Await()
  1608. resNetZoneRequests, _ := resChNetZoneRequests.Await()
  1609. resNetRegionRequests, _ := resChNetRegionRequests.Await()
  1610. resNetInternetRequests, _ := resChNetInternetRequests.Await()
  1611. resNSLabels, _ := resChNSLabels.Await()
  1612. resPodLabels, _ := resChPodLabels.Await()
  1613. resNSAnnotations, _ := resChNSAnnotations.Await()
  1614. resPodAnnotations, _ := resChPodAnnotations.Await()
  1615. resServiceLabels, _ := resChServiceLabels.Await()
  1616. resDeploymentLabels, _ := resChDeploymentLabels.Await()
  1617. resStatefulsetLabels, _ := resChStatefulsetLabels.Await()
  1618. resDaemonsets, _ := resChDaemonsets.Await()
  1619. resJobs, _ := resChJobs.Await()
  1620. resNormalization, _ := resChNormalization.Await()
  1621. // NOTE: The way we currently handle errors and warnings only early returns if there is an error. Warnings
  1622. // NOTE: will not propagate unless coupled with errors.
  1623. if ctx.HasErrors() {
  1624. // To keep the context of where the errors are occurring, we log the errors here and pass them the error
  1625. // back to the caller. The caller should handle the specific case where error is an ErrorCollection
  1626. for _, promErr := range ctx.Errors() {
  1627. if promErr.Error != nil {
  1628. log.Errorf("CostDataRange: Request Error: %s", promErr.Error)
  1629. }
  1630. if promErr.ParseError != nil {
  1631. log.Errorf("CostDataRange: Parsing Error: %s", promErr.ParseError)
  1632. }
  1633. }
  1634. // ErrorCollection is an collection of errors wrapped in a single error implementation
  1635. return nil, ctx.ErrorCollection()
  1636. }
  1637. normalizationValue, err := getNormalizations(resNormalization)
  1638. if err != nil {
  1639. msg := fmt.Sprintf("error computing normalization for start=%s, end=%s, res=%s", start, end, resolution)
  1640. return nil, prom.WrapError(err, msg)
  1641. }
  1642. pvClaimMapping, err := GetPVInfo(resPVRequests, clusterID)
  1643. if err != nil {
  1644. // Just log for compatibility with KSM less than 1.6
  1645. log.Infof("Unable to get PV Data: %s", err.Error())
  1646. }
  1647. if pvClaimMapping != nil {
  1648. err = addPVData(cm.Cache, pvClaimMapping, cp)
  1649. if err != nil {
  1650. return nil, fmt.Errorf("pvClaimMapping: %s", err)
  1651. }
  1652. }
  1653. pvCostMapping, err := GetPVCostMetrics(resPVHourlyCost, clusterID)
  1654. if err != nil {
  1655. log.Errorf("Unable to get PV Hourly Cost Data: %s", err.Error())
  1656. }
  1657. unmountedPVs := make(map[string][]*PersistentVolumeClaimData)
  1658. pvAllocationMapping, err := GetPVAllocationMetrics(resPVCAlloc, clusterID)
  1659. if err != nil {
  1660. log.Errorf("Unable to get PV Allocation Cost Data: %s", err.Error())
  1661. }
  1662. if pvAllocationMapping != nil {
  1663. addMetricPVData(pvAllocationMapping, pvCostMapping, cp)
  1664. for k, v := range pvAllocationMapping {
  1665. unmountedPVs[k] = v
  1666. }
  1667. }
  1668. nsLabels, err := GetNamespaceLabelsMetrics(resNSLabels, clusterID)
  1669. if err != nil {
  1670. log.Errorf("Unable to get Namespace Labels for Metrics: %s", err.Error())
  1671. }
  1672. if nsLabels != nil {
  1673. mergeStringMap(namespaceLabelsMapping, nsLabels)
  1674. }
  1675. podLabels, err := GetPodLabelsMetrics(resPodLabels, clusterID)
  1676. if err != nil {
  1677. log.Errorf("Unable to get Pod Labels for Metrics: %s", err.Error())
  1678. }
  1679. nsAnnotations, err := GetNamespaceAnnotationsMetrics(resNSAnnotations, clusterID)
  1680. if err != nil {
  1681. log.Errorf("Unable to get Namespace Annotations for Metrics: %s", err.Error())
  1682. }
  1683. if nsAnnotations != nil {
  1684. mergeStringMap(namespaceAnnotationsMapping, nsAnnotations)
  1685. }
  1686. podAnnotations, err := GetPodAnnotationsMetrics(resPodAnnotations, clusterID)
  1687. if err != nil {
  1688. log.Errorf("Unable to get Pod Annotations for Metrics: %s", err.Error())
  1689. }
  1690. serviceLabels, err := GetServiceSelectorLabelsMetrics(resServiceLabels, clusterID)
  1691. if err != nil {
  1692. log.Errorf("Unable to get Service Selector Labels for Metrics: %s", err.Error())
  1693. }
  1694. deploymentLabels, err := GetDeploymentMatchLabelsMetrics(resDeploymentLabels, clusterID)
  1695. if err != nil {
  1696. log.Errorf("Unable to get Deployment Match Labels for Metrics: %s", err.Error())
  1697. }
  1698. statefulsetLabels, err := GetStatefulsetMatchLabelsMetrics(resStatefulsetLabels, clusterID)
  1699. if err != nil {
  1700. log.Errorf("Unable to get Deployment Match Labels for Metrics: %s", err.Error())
  1701. }
  1702. podStatefulsetMetricsMapping, err := getPodDeploymentsWithMetrics(statefulsetLabels, podLabels)
  1703. if err != nil {
  1704. log.Errorf("Unable to get match Statefulset Labels Metrics to Pods: %s", err.Error())
  1705. }
  1706. appendLabelsList(podStatefulsetsMapping, podStatefulsetMetricsMapping)
  1707. podDeploymentsMetricsMapping, err := getPodDeploymentsWithMetrics(deploymentLabels, podLabels)
  1708. if err != nil {
  1709. log.Errorf("Unable to get match Deployment Labels Metrics to Pods: %s", err.Error())
  1710. }
  1711. appendLabelsList(podDeploymentsMapping, podDeploymentsMetricsMapping)
  1712. podDaemonsets, err := GetPodDaemonsetsWithMetrics(resDaemonsets, clusterID)
  1713. if err != nil {
  1714. log.Errorf("Unable to get Pod Daemonsets for Metrics: %s", err.Error())
  1715. }
  1716. podJobs, err := GetPodJobsWithMetrics(resJobs, clusterID)
  1717. if err != nil {
  1718. log.Errorf("Unable to get Pod Jobs for Metrics: %s", err.Error())
  1719. }
  1720. podServicesMetricsMapping, err := getPodServicesWithMetrics(serviceLabels, podLabels)
  1721. if err != nil {
  1722. log.Errorf("Unable to get match Service Labels Metrics to Pods: %s", err.Error())
  1723. }
  1724. appendLabelsList(podServicesMapping, podServicesMetricsMapping)
  1725. networkUsageMap, err := GetNetworkUsageData(resNetZoneRequests, resNetRegionRequests, resNetInternetRequests, clusterID)
  1726. if err != nil {
  1727. log.Errorf("Unable to get Network Cost Data: %s", err.Error())
  1728. networkUsageMap = make(map[string]*NetworkUsageData)
  1729. }
  1730. containerNameCost := make(map[string]*CostData)
  1731. containers := make(map[string]bool)
  1732. otherClusterPVRecorded := make(map[string]bool)
  1733. RAMReqMap, err := GetNormalizedContainerMetricVectors(resRAMRequests, normalizationValue, clusterID)
  1734. if err != nil {
  1735. return nil, prom.WrapError(err, "GetNormalizedContainerMetricVectors(RAMRequests)")
  1736. }
  1737. for key := range RAMReqMap {
  1738. containers[key] = true
  1739. }
  1740. RAMUsedMap, err := GetNormalizedContainerMetricVectors(resRAMUsage, normalizationValue, clusterID)
  1741. if err != nil {
  1742. return nil, prom.WrapError(err, "GetNormalizedContainerMetricVectors(RAMUsage)")
  1743. }
  1744. for key := range RAMUsedMap {
  1745. containers[key] = true
  1746. }
  1747. CPUReqMap, err := GetNormalizedContainerMetricVectors(resCPURequests, normalizationValue, clusterID)
  1748. if err != nil {
  1749. return nil, prom.WrapError(err, "GetNormalizedContainerMetricVectors(CPURequests)")
  1750. }
  1751. for key := range CPUReqMap {
  1752. containers[key] = true
  1753. }
  1754. // No need to normalize here, as this comes from a counter, namely:
  1755. // rate(container_cpu_usage_seconds_total) which properly accounts for normalized rates
  1756. CPUUsedMap, err := GetContainerMetricVectors(resCPUUsage, clusterID)
  1757. if err != nil {
  1758. return nil, prom.WrapError(err, "GetContainerMetricVectors(CPUUsage)")
  1759. }
  1760. for key := range CPUUsedMap {
  1761. containers[key] = true
  1762. }
  1763. RAMAllocMap, err := GetContainerMetricVectors(resRAMAlloc, clusterID)
  1764. if err != nil {
  1765. return nil, prom.WrapError(err, "GetContainerMetricVectors(RAMAllocations)")
  1766. }
  1767. for key := range RAMAllocMap {
  1768. containers[key] = true
  1769. }
  1770. CPUAllocMap, err := GetContainerMetricVectors(resCPUAlloc, clusterID)
  1771. if err != nil {
  1772. return nil, prom.WrapError(err, "GetContainerMetricVectors(CPUAllocations)")
  1773. }
  1774. for key := range CPUAllocMap {
  1775. containers[key] = true
  1776. }
  1777. GPUReqMap, err := GetNormalizedContainerMetricVectors(resGPURequests, normalizationValue, clusterID)
  1778. if err != nil {
  1779. return nil, prom.WrapError(err, "GetContainerMetricVectors(GPURequests)")
  1780. }
  1781. for key := range GPUReqMap {
  1782. containers[key] = true
  1783. }
  1784. // Request metrics can show up after pod eviction and completion.
  1785. // This method synchronizes requests to allocations such that when
  1786. // allocation is 0, so are requests
  1787. applyAllocationToRequests(RAMAllocMap, RAMReqMap)
  1788. applyAllocationToRequests(CPUAllocMap, CPUReqMap)
  1789. missingNodes := make(map[string]*costAnalyzerCloud.Node)
  1790. missingContainers := make(map[string]*CostData)
  1791. for key := range containers {
  1792. if _, ok := containerNameCost[key]; ok {
  1793. continue // because ordering is important for the allocation model (all PV's applied to the first), just dedupe if it's already been added.
  1794. }
  1795. c, _ := NewContainerMetricFromKey(key)
  1796. RAMReqV, ok := RAMReqMap[key]
  1797. if !ok {
  1798. log.Debug("no RAM requests for " + key)
  1799. RAMReqV = []*util.Vector{}
  1800. }
  1801. RAMUsedV, ok := RAMUsedMap[key]
  1802. if !ok {
  1803. log.Debug("no RAM usage for " + key)
  1804. RAMUsedV = []*util.Vector{}
  1805. }
  1806. CPUReqV, ok := CPUReqMap[key]
  1807. if !ok {
  1808. log.Debug("no CPU requests for " + key)
  1809. CPUReqV = []*util.Vector{}
  1810. }
  1811. CPUUsedV, ok := CPUUsedMap[key]
  1812. if !ok {
  1813. log.Debug("no CPU usage for " + key)
  1814. CPUUsedV = []*util.Vector{}
  1815. }
  1816. RAMAllocsV, ok := RAMAllocMap[key]
  1817. if !ok {
  1818. log.Debug("no RAM allocation for " + key)
  1819. RAMAllocsV = []*util.Vector{}
  1820. }
  1821. CPUAllocsV, ok := CPUAllocMap[key]
  1822. if !ok {
  1823. log.Debug("no CPU allocation for " + key)
  1824. CPUAllocsV = []*util.Vector{}
  1825. }
  1826. GPUReqV, ok := GPUReqMap[key]
  1827. if !ok {
  1828. log.Debug("no GPU requests for " + key)
  1829. GPUReqV = []*util.Vector{}
  1830. }
  1831. var node *costAnalyzerCloud.Node
  1832. if n, ok := missingNodes[c.NodeName]; ok {
  1833. node = n
  1834. } else {
  1835. node = &costAnalyzerCloud.Node{}
  1836. missingNodes[c.NodeName] = node
  1837. }
  1838. nsKey := c.Namespace + "," + c.ClusterID
  1839. podKey := c.Namespace + "," + c.PodName + "," + c.ClusterID
  1840. namespaceLabels, _ := namespaceLabelsMapping[nsKey]
  1841. pLabels := podLabels[podKey]
  1842. if pLabels == nil {
  1843. pLabels = make(map[string]string)
  1844. }
  1845. for k, v := range namespaceLabels {
  1846. if _, ok := pLabels[k]; !ok {
  1847. pLabels[k] = v
  1848. }
  1849. }
  1850. namespaceAnnotations, _ := namespaceAnnotationsMapping[nsKey]
  1851. pAnnotations := podAnnotations[podKey]
  1852. if pAnnotations == nil {
  1853. pAnnotations = make(map[string]string)
  1854. }
  1855. for k, v := range namespaceAnnotations {
  1856. if _, ok := pAnnotations[k]; !ok {
  1857. pAnnotations[k] = v
  1858. }
  1859. }
  1860. var podDeployments []string
  1861. if _, ok := podDeploymentsMapping[nsKey]; ok {
  1862. if ds, ok := podDeploymentsMapping[nsKey][c.PodName]; ok {
  1863. podDeployments = ds
  1864. } else {
  1865. podDeployments = []string{}
  1866. }
  1867. }
  1868. var podStatefulSets []string
  1869. if _, ok := podStatefulsetsMapping[nsKey]; ok {
  1870. if ss, ok := podStatefulsetsMapping[nsKey][c.PodName]; ok {
  1871. podStatefulSets = ss
  1872. } else {
  1873. podStatefulSets = []string{}
  1874. }
  1875. }
  1876. var podServices []string
  1877. if _, ok := podServicesMapping[nsKey]; ok {
  1878. if svcs, ok := podServicesMapping[nsKey][c.PodName]; ok {
  1879. podServices = svcs
  1880. } else {
  1881. podServices = []string{}
  1882. }
  1883. }
  1884. var podPVs []*PersistentVolumeClaimData
  1885. var podNetCosts []*util.Vector
  1886. // For PVC data, we'll need to find the claim mapping and cost data. Will need to append
  1887. // cost data since that was populated by cluster data previously. We do this with
  1888. // the pod_pvc_allocation metric
  1889. podPVData, ok := pvAllocationMapping[podKey]
  1890. if !ok {
  1891. log.Debugf("Failed to locate pv allocation mapping for missing pod.")
  1892. }
  1893. // Delete the current pod key from potentially unmounted pvs
  1894. delete(unmountedPVs, podKey)
  1895. // For network costs, we'll use existing map since it should still contain the
  1896. // correct data.
  1897. var podNetworkCosts []*util.Vector
  1898. if usage, ok := networkUsageMap[podKey]; ok {
  1899. netCosts, err := GetNetworkCost(usage, cp)
  1900. if err != nil {
  1901. log.Errorf("Error pulling network costs: %s", err.Error())
  1902. } else {
  1903. podNetworkCosts = netCosts
  1904. }
  1905. }
  1906. // Check to see if any other data has been recorded for this namespace, pod, clusterId
  1907. // Follow the pattern of only allowing claims data per pod
  1908. if !otherClusterPVRecorded[podKey] {
  1909. otherClusterPVRecorded[podKey] = true
  1910. podPVs = podPVData
  1911. podNetCosts = podNetworkCosts
  1912. }
  1913. pds := []string{}
  1914. if ds, ok := podDaemonsets[podKey]; ok {
  1915. pds = []string{ds}
  1916. }
  1917. jobs := []string{}
  1918. if job, ok := podJobs[podKey]; ok {
  1919. jobs = []string{job}
  1920. }
  1921. costs := &CostData{
  1922. Name: c.ContainerName,
  1923. PodName: c.PodName,
  1924. NodeName: c.NodeName,
  1925. NodeData: node,
  1926. Namespace: c.Namespace,
  1927. Services: podServices,
  1928. Deployments: podDeployments,
  1929. Daemonsets: pds,
  1930. Statefulsets: podStatefulSets,
  1931. Jobs: jobs,
  1932. RAMReq: RAMReqV,
  1933. RAMUsed: RAMUsedV,
  1934. CPUReq: CPUReqV,
  1935. CPUUsed: CPUUsedV,
  1936. RAMAllocation: RAMAllocsV,
  1937. CPUAllocation: CPUAllocsV,
  1938. GPUReq: GPUReqV,
  1939. Annotations: pAnnotations,
  1940. Labels: pLabels,
  1941. NamespaceLabels: namespaceLabels,
  1942. PVCData: podPVs,
  1943. NetworkData: podNetCosts,
  1944. ClusterID: c.ClusterID,
  1945. ClusterName: cm.ClusterMap.NameFor(c.ClusterID),
  1946. }
  1947. if costDataPassesFilters(cm.ClusterMap, costs, filterNamespace, filterCluster) {
  1948. containerNameCost[key] = costs
  1949. missingContainers[key] = costs
  1950. }
  1951. }
  1952. unmounted := findUnmountedPVCostData(cm.ClusterMap, unmountedPVs, namespaceLabelsMapping, namespaceAnnotationsMapping)
  1953. for k, costs := range unmounted {
  1954. log.Debugf("Unmounted PVs in Namespace/ClusterID: %s/%s", costs.Namespace, costs.ClusterID)
  1955. if costDataPassesFilters(cm.ClusterMap, costs, filterNamespace, filterCluster) {
  1956. containerNameCost[k] = costs
  1957. }
  1958. }
  1959. if window.Minutes() > 0 {
  1960. dur, off := window.DurationOffsetStrings()
  1961. err = findDeletedNodeInfo(cli, missingNodes, dur, off)
  1962. if err != nil {
  1963. log.Errorf("Error fetching historical node data: %s", err.Error())
  1964. }
  1965. }
  1966. return containerNameCost, nil
  1967. }
  1968. func applyAllocationToRequests(allocationMap map[string][]*util.Vector, requestMap map[string][]*util.Vector) {
  1969. // The result of the normalize operation will be a new []*util.Vector to replace the requests
  1970. normalizeOp := func(r *util.Vector, x *float64, y *float64) bool {
  1971. // Omit data (return false) if both x and y inputs don't exist
  1972. if x == nil || y == nil {
  1973. return false
  1974. }
  1975. // If the allocation value is 0, 0 out request value
  1976. if *x == 0 {
  1977. r.Value = 0
  1978. } else {
  1979. r.Value = *y
  1980. }
  1981. return true
  1982. }
  1983. // Run normalization on all request vectors in the mapping
  1984. for k, requests := range requestMap {
  1985. // Only run normalization where there are valid allocations
  1986. allocations, ok := allocationMap[k]
  1987. if !ok {
  1988. delete(requestMap, k)
  1989. continue
  1990. }
  1991. // Replace request map with normalized
  1992. requestMap[k] = util.ApplyVectorOp(allocations, requests, normalizeOp)
  1993. }
  1994. }
  1995. func addMetricPVData(pvAllocationMap map[string][]*PersistentVolumeClaimData, pvCostMap map[string]*costAnalyzerCloud.PV, cp costAnalyzerCloud.Provider) {
  1996. cfg, err := cp.GetConfig()
  1997. if err != nil {
  1998. log.Errorf("Failed to get provider config while adding pv metrics data.")
  1999. return
  2000. }
  2001. for _, pvcDataArray := range pvAllocationMap {
  2002. for _, pvcData := range pvcDataArray {
  2003. costKey := fmt.Sprintf("%s,%s", pvcData.VolumeName, pvcData.ClusterID)
  2004. pvCost, ok := pvCostMap[costKey]
  2005. if !ok {
  2006. pvcData.Volume = &costAnalyzerCloud.PV{
  2007. Cost: cfg.Storage,
  2008. }
  2009. continue
  2010. }
  2011. pvcData.Volume = pvCost
  2012. }
  2013. }
  2014. }
  2015. // Add values that don't already exist in origMap from mergeMap into origMap
  2016. func mergeStringMap(origMap map[string]map[string]string, mergeMap map[string]map[string]string) {
  2017. for k, v := range mergeMap {
  2018. if _, ok := origMap[k]; !ok {
  2019. origMap[k] = v
  2020. }
  2021. }
  2022. }
  2023. func appendLabelsList(mainLabels map[string]map[string][]string, labels map[string]map[string][]string) {
  2024. for k, v := range labels {
  2025. mainLabels[k] = v
  2026. }
  2027. }
  2028. func getNamespaceLabels(cache clustercache.ClusterCache, clusterID string) (map[string]map[string]string, error) {
  2029. nsToLabels := make(map[string]map[string]string)
  2030. nss := cache.GetAllNamespaces()
  2031. for _, ns := range nss {
  2032. labels := make(map[string]string)
  2033. for k, v := range ns.Labels {
  2034. labels[promutil.SanitizeLabelName(k)] = v
  2035. }
  2036. nsToLabels[ns.Name+","+clusterID] = labels
  2037. }
  2038. return nsToLabels, nil
  2039. }
  2040. func getNamespaceAnnotations(cache clustercache.ClusterCache, clusterID string) (map[string]map[string]string, error) {
  2041. nsToAnnotations := make(map[string]map[string]string)
  2042. nss := cache.GetAllNamespaces()
  2043. for _, ns := range nss {
  2044. annotations := make(map[string]string)
  2045. for k, v := range ns.Annotations {
  2046. annotations[promutil.SanitizeLabelName(k)] = v
  2047. }
  2048. nsToAnnotations[ns.Name+","+clusterID] = annotations
  2049. }
  2050. return nsToAnnotations, nil
  2051. }
  2052. func getDaemonsetsOfPod(pod v1.Pod) []string {
  2053. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  2054. if ownerReference.Kind == "DaemonSet" {
  2055. return []string{ownerReference.Name}
  2056. }
  2057. }
  2058. return []string{}
  2059. }
  2060. func getJobsOfPod(pod v1.Pod) []string {
  2061. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  2062. if ownerReference.Kind == "Job" {
  2063. return []string{ownerReference.Name}
  2064. }
  2065. }
  2066. return []string{}
  2067. }
  2068. func getStatefulSetsOfPod(pod v1.Pod) []string {
  2069. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  2070. if ownerReference.Kind == "StatefulSet" {
  2071. return []string{ownerReference.Name}
  2072. }
  2073. }
  2074. return []string{}
  2075. }
  2076. func getAllocatableVGPUs(cache clustercache.ClusterCache) (float64, error) {
  2077. daemonsets := cache.GetAllDaemonSets()
  2078. vgpuCount := 0.0
  2079. for _, ds := range daemonsets {
  2080. dsContainerList := &ds.Spec.Template.Spec.Containers
  2081. for _, ctnr := range *dsContainerList {
  2082. if ctnr.Args != nil {
  2083. for _, arg := range ctnr.Args {
  2084. if strings.Contains(arg, "--vgpu=") {
  2085. vgpus, err := strconv.ParseFloat(arg[strings.IndexByte(arg, '=')+1:], 64)
  2086. if err != nil {
  2087. log.Errorf("failed to parse vgpu allocation string %s: %v", arg, err)
  2088. continue
  2089. }
  2090. vgpuCount = vgpus
  2091. return vgpuCount, nil
  2092. }
  2093. }
  2094. }
  2095. }
  2096. }
  2097. return vgpuCount, nil
  2098. }
  2099. type PersistentVolumeClaimData struct {
  2100. Class string `json:"class"`
  2101. Claim string `json:"claim"`
  2102. Namespace string `json:"namespace"`
  2103. ClusterID string `json:"clusterId"`
  2104. TimesClaimed int `json:"timesClaimed"`
  2105. VolumeName string `json:"volumeName"`
  2106. Volume *costAnalyzerCloud.PV `json:"persistentVolume"`
  2107. Values []*util.Vector `json:"values"`
  2108. }
  2109. func measureTime(start time.Time, threshold time.Duration, name string) {
  2110. elapsed := time.Since(start)
  2111. if elapsed > threshold {
  2112. log.Infof("[Profiler] %s: %s", elapsed, name)
  2113. }
  2114. }
  2115. func measureTimeAsync(start time.Time, threshold time.Duration, name string, ch chan string) {
  2116. elapsed := time.Since(start)
  2117. if elapsed > threshold {
  2118. ch <- fmt.Sprintf("%s took %s", name, time.Since(start))
  2119. }
  2120. }
  2121. func (cm *CostModel) QueryAllocation(window opencost.Window, resolution, step time.Duration, aggregate []string, includeIdle, idleByNode, includeProportionalAssetResourceCosts, includeAggregatedMetadata, sharedLoadBalancer bool, accumulateBy opencost.AccumulateOption) (*opencost.AllocationSetRange, error) {
  2122. // Validate window is legal
  2123. if window.IsOpen() || window.IsNegative() {
  2124. return nil, fmt.Errorf("illegal window: %s", window)
  2125. }
  2126. var totalsStore opencost.TotalsStore
  2127. // Idle is required for proportional asset costs
  2128. if includeProportionalAssetResourceCosts {
  2129. if !includeIdle {
  2130. return nil, errors.New("bad request - includeIdle must be set true if includeProportionalAssetResourceCosts is true")
  2131. }
  2132. totalsStore = opencost.NewMemoryTotalsStore()
  2133. }
  2134. // Begin with empty response
  2135. asr := opencost.NewAllocationSetRange()
  2136. // Query for AllocationSets in increments of the given step duration,
  2137. // appending each to the response.
  2138. stepStart := *window.Start()
  2139. stepEnd := stepStart.Add(step)
  2140. var isAKS bool
  2141. for window.End().After(stepStart) {
  2142. allocSet, err := cm.ComputeAllocation(stepStart, stepEnd, resolution)
  2143. if err != nil {
  2144. return nil, fmt.Errorf("error computing allocations for %s: %w", opencost.NewClosedWindow(stepStart, stepEnd), err)
  2145. }
  2146. if includeIdle {
  2147. assetSet, err := cm.ComputeAssets(stepStart, stepEnd)
  2148. if err != nil {
  2149. return nil, fmt.Errorf("error computing assets for %s: %w", opencost.NewClosedWindow(stepStart, stepEnd), err)
  2150. }
  2151. if includeProportionalAssetResourceCosts {
  2152. // AKS is a special case - there can be a maximum of 2
  2153. // load balancers (1 public and 1 private) in an AKS cluster
  2154. // therefore, when calculating PARCs for load balancers,
  2155. // we must know if this is an AKS cluster
  2156. for _, node := range assetSet.Nodes {
  2157. if _, found := node.Labels["label_kubernetes_azure_com_cluster"]; found {
  2158. isAKS = true
  2159. break
  2160. }
  2161. }
  2162. _, err := opencost.UpdateAssetTotalsStore(totalsStore, assetSet)
  2163. if err != nil {
  2164. log.Errorf("ETL: error updating asset resource totals for %s: %s", assetSet.Window, err)
  2165. }
  2166. }
  2167. idleSet, err := computeIdleAllocations(allocSet, assetSet, true)
  2168. if err != nil {
  2169. return nil, fmt.Errorf("error computing idle allocations for %s: %w", opencost.NewClosedWindow(stepStart, stepEnd), err)
  2170. }
  2171. for _, idleAlloc := range idleSet.Allocations {
  2172. allocSet.Insert(idleAlloc)
  2173. }
  2174. }
  2175. asr.Append(allocSet)
  2176. stepStart = stepEnd
  2177. stepEnd = stepStart.Add(step)
  2178. }
  2179. // Set aggregation options and aggregate
  2180. opts := &opencost.AllocationAggregationOptions{
  2181. IncludeProportionalAssetResourceCosts: includeProportionalAssetResourceCosts,
  2182. IdleByNode: idleByNode,
  2183. IncludeAggregatedMetadata: includeAggregatedMetadata,
  2184. }
  2185. // Aggregate
  2186. err := asr.AggregateBy(aggregate, opts)
  2187. if err != nil {
  2188. return nil, fmt.Errorf("error aggregating for %s: %w", window, err)
  2189. }
  2190. // Accumulate, if requested
  2191. if accumulateBy != opencost.AccumulateOptionNone {
  2192. asr, err = asr.Accumulate(accumulateBy)
  2193. if err != nil {
  2194. log.Errorf("error accumulating by %v: %s", accumulateBy, err)
  2195. return nil, fmt.Errorf("error accumulating by %v: %s", accumulateBy, err)
  2196. }
  2197. // when accumulating and returning PARCs, we need the totals for the
  2198. // accumulated windows to accurately compute a fraction
  2199. if includeProportionalAssetResourceCosts {
  2200. assetSet, err := cm.ComputeAssets(*asr.Window().Start(), *asr.Window().End())
  2201. if err != nil {
  2202. return nil, fmt.Errorf("error computing assets for %s: %w", opencost.NewClosedWindow(*asr.Window().Start(), *asr.Window().End()), err)
  2203. }
  2204. _, err = opencost.UpdateAssetTotalsStore(totalsStore, assetSet)
  2205. if err != nil {
  2206. log.Errorf("ETL: error updating asset resource totals for %s: %s", opencost.NewClosedWindow(*asr.Window().Start(), *asr.Window().End()), err)
  2207. }
  2208. }
  2209. }
  2210. if includeProportionalAssetResourceCosts {
  2211. for _, as := range asr.Allocations {
  2212. totalStoreByNode, ok := totalsStore.GetAssetTotalsByNode(as.Start(), as.End())
  2213. if !ok {
  2214. log.Errorf("unable to locate allocation totals for node for window %v - %v", as.Start(), as.End())
  2215. return nil, fmt.Errorf("unable to locate allocation totals for node for window %v - %v", as.Start(), as.End())
  2216. }
  2217. totalStoreByCluster, ok := totalsStore.GetAssetTotalsByCluster(as.Start(), as.End())
  2218. if !ok {
  2219. log.Errorf("unable to locate allocation totals for cluster for window %v - %v", as.Start(), as.End())
  2220. return nil, fmt.Errorf("unable to locate allocation totals for cluster for window %v - %v", as.Start(), as.End())
  2221. }
  2222. var totalPublicLbCost, totalPrivateLbCost float64
  2223. if isAKS && sharedLoadBalancer {
  2224. // loop through all assetTotals, adding all load balancer costs by public and private
  2225. for _, tot := range totalStoreByNode {
  2226. if tot.PrivateLoadBalancer {
  2227. totalPrivateLbCost += tot.LoadBalancerCost
  2228. } else {
  2229. totalPublicLbCost += tot.LoadBalancerCost
  2230. }
  2231. }
  2232. }
  2233. // loop through each allocation set, using total cost from totals store
  2234. for _, alloc := range as.Allocations {
  2235. for rawKey, parc := range alloc.ProportionalAssetResourceCosts {
  2236. key := strings.TrimSuffix(strings.ReplaceAll(rawKey, ",", "/"), "/")
  2237. // for each parc , check the totals store for each
  2238. // on a totals hit, set the corresponding total and calculate percentage
  2239. var totals *opencost.AssetTotals
  2240. if totalsLoc, found := totalStoreByCluster[key]; found {
  2241. totals = totalsLoc
  2242. }
  2243. if totalsLoc, found := totalStoreByNode[key]; found {
  2244. totals = totalsLoc
  2245. }
  2246. if totals == nil {
  2247. log.Errorf("unable to locate asset totals for allocation %s, corresponding PARC is being skipped", key)
  2248. continue
  2249. }
  2250. parc.CPUTotalCost = totals.CPUCost
  2251. parc.GPUTotalCost = totals.GPUCost
  2252. parc.RAMTotalCost = totals.RAMCost
  2253. parc.PVTotalCost = totals.PersistentVolumeCost
  2254. if isAKS && sharedLoadBalancer && len(alloc.LoadBalancers) > 0 {
  2255. // Azure is a special case - use computed totals above
  2256. // use the lbAllocations in the object to determine if
  2257. // this PARC is a public or private load balancer
  2258. // then set the total accordingly
  2259. // AKS only has 1 public and 1 private load balancer
  2260. lbAlloc, found := alloc.LoadBalancers[key]
  2261. if found {
  2262. if lbAlloc.Private {
  2263. parc.LoadBalancerTotalCost = totalPrivateLbCost
  2264. } else {
  2265. parc.LoadBalancerTotalCost = totalPublicLbCost
  2266. }
  2267. }
  2268. } else {
  2269. parc.LoadBalancerTotalCost = totals.LoadBalancerCost
  2270. }
  2271. opencost.ComputePercentages(&parc)
  2272. alloc.ProportionalAssetResourceCosts[rawKey] = parc
  2273. }
  2274. }
  2275. }
  2276. }
  2277. return asr, nil
  2278. }
  2279. func computeIdleAllocations(allocSet *opencost.AllocationSet, assetSet *opencost.AssetSet, idleByNode bool) (*opencost.AllocationSet, error) {
  2280. if !allocSet.Window.Equal(assetSet.Window) {
  2281. return nil, fmt.Errorf("cannot compute idle allocations for mismatched sets: %s does not equal %s", allocSet.Window, assetSet.Window)
  2282. }
  2283. var allocTotals map[string]*opencost.AllocationTotals
  2284. var assetTotals map[string]*opencost.AssetTotals
  2285. if idleByNode {
  2286. allocTotals = opencost.ComputeAllocationTotals(allocSet, opencost.AllocationNodeProp)
  2287. assetTotals = opencost.ComputeAssetTotals(assetSet, true)
  2288. } else {
  2289. allocTotals = opencost.ComputeAllocationTotals(allocSet, opencost.AllocationClusterProp)
  2290. assetTotals = opencost.ComputeAssetTotals(assetSet, false)
  2291. }
  2292. start, end := *allocSet.Window.Start(), *allocSet.Window.End()
  2293. idleSet := opencost.NewAllocationSet(start, end)
  2294. for key, assetTotal := range assetTotals {
  2295. allocTotal, ok := allocTotals[key]
  2296. if !ok {
  2297. log.Warnf("ETL: did not find allocations for asset key: %s", key)
  2298. // Use a zero-value set of totals. This indicates either (1) an
  2299. // error computing totals, or (2) that no allocations ran on the
  2300. // given node for the given window.
  2301. allocTotal = &opencost.AllocationTotals{
  2302. Cluster: assetTotal.Cluster,
  2303. Node: assetTotal.Node,
  2304. Start: assetTotal.Start,
  2305. End: assetTotal.End,
  2306. }
  2307. }
  2308. // Insert one idle allocation for each key (whether by node or
  2309. // by cluster), defined as the difference between the total
  2310. // asset cost and the allocated cost per-resource.
  2311. name := fmt.Sprintf("%s/%s", key, opencost.IdleSuffix)
  2312. err := idleSet.Insert(&opencost.Allocation{
  2313. Name: name,
  2314. Window: idleSet.Window.Clone(),
  2315. Properties: &opencost.AllocationProperties{
  2316. Cluster: assetTotal.Cluster,
  2317. Node: assetTotal.Node,
  2318. ProviderID: assetTotal.Node,
  2319. },
  2320. Start: assetTotal.Start,
  2321. End: assetTotal.End,
  2322. CPUCost: assetTotal.TotalCPUCost() - allocTotal.TotalCPUCost(),
  2323. GPUCost: assetTotal.TotalGPUCost() - allocTotal.TotalGPUCost(),
  2324. RAMCost: assetTotal.TotalRAMCost() - allocTotal.TotalRAMCost(),
  2325. })
  2326. if err != nil {
  2327. return nil, fmt.Errorf("failed to insert idle allocation %s: %w", name, err)
  2328. }
  2329. }
  2330. return idleSet, nil
  2331. }